diff --git a/sdk/rdbms/azure-mgmt-rdbms/_meta.json b/sdk/rdbms/azure-mgmt-rdbms/_meta.json index 7f79724060fb..ccca82b73ac4 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": "e2b0566eacae5b5ed89362799cc1b27c88325c76", + "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.2.1", + "@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", - "readme": "specification/mysql/resource-manager/readme.md" + "autorest_command": "autorest specification/postgresql/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.2.1 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "readme": "specification/postgresql/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/__init__.py index 64e2cc211b0f..473b3c5678d9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/__init__.py @@ -17,7 +17,10 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['PostgreSQLManagementClient'] + +__all__ = [ + "PostgreSQLManagementClient", +] __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/postgresql/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_configuration.py index 085b7fa5ba51..170069720193 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_configuration.py @@ -25,18 +25,13 @@ class PostgreSQLManagementClientConfiguration(Configuration): # pylint: disable 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(PostgreSQLManagementClientConfiguration, 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/postgresql/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_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/postgresql/_postgre_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_postgre_sql_management_client.py index 16428ff093ee..40b1ad165ada 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_postgre_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_postgre_sql_management_client.py @@ -9,20 +9,39 @@ 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 PostgreSQLManagementClientConfiguration -from .operations import CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, LocationBasedPerformanceTierOperations, LogFilesOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, RecoverableServersOperations, ReplicasOperations, ServerAdministratorsOperations, ServerBasedPerformanceTierOperations, ServerKeysOperations, ServerParametersOperations, ServerSecurityAlertPoliciesOperations, ServersOperations, VirtualNetworkRulesOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + CheckNameAvailabilityOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + LocationBasedPerformanceTierOperations, + LogFilesOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + RecoverableServersOperations, + ReplicasOperations, + ServerAdministratorsOperations, + ServerBasedPerformanceTierOperations, + ServerKeysOperations, + ServerParametersOperations, + ServerSecurityAlertPoliciesOperations, + ServersOperations, + VirtualNetworkRulesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class PostgreSQLManagementClient: # pylint: disable=too-many-instance-attributes + +class PostgreSQLManagementClient: # 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 PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. @@ -72,9 +91,9 @@ class PostgreSQLManagementClient: # pylint: disable=too-many-instance-attribu azure.mgmt.rdbms.postgresql.operations.PrivateLinkResourcesOperations :ivar server_keys: ServerKeysOperations operations :vartype server_keys: azure.mgmt.rdbms.postgresql.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 @@ -89,37 +108,27 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = PostgreSQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = PostgreSQLManagementClientConfiguration( + 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 ) @@ -135,9 +144,7 @@ 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 ) @@ -147,16 +154,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 @@ -165,7 +165,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/postgresql/_serialization.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_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/postgresql/_vendor.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_vendor.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_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/postgresql/_version.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_version.py index a172f504a7eb..e5754a47ce68 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_version.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/_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/postgresql/aio/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/__init__.py index 6d35026eff99..a3ea1a85dcd9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/__init__.py @@ -14,7 +14,10 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['PostgreSQLManagementClient'] + +__all__ = [ + "PostgreSQLManagementClient", +] __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/postgresql/aio/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_configuration.py index 1e909bbb2240..d68b5dbe01c6 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_configuration.py @@ -25,18 +25,13 @@ class PostgreSQLManagementClientConfiguration(Configuration): # pylint: disable 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(PostgreSQLManagementClientConfiguration, 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/postgresql/aio/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_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/postgresql/aio/_postgre_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_postgre_sql_management_client.py index db2c9be69c24..59ffbae0b95b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_postgre_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/_postgre_sql_management_client.py @@ -9,20 +9,39 @@ 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 PostgreSQLManagementClientConfiguration -from .operations import CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, LocationBasedPerformanceTierOperations, LogFilesOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, RecoverableServersOperations, ReplicasOperations, ServerAdministratorsOperations, ServerBasedPerformanceTierOperations, ServerKeysOperations, ServerParametersOperations, ServerSecurityAlertPoliciesOperations, ServersOperations, VirtualNetworkRulesOperations +from .operations import ( + CheckNameAvailabilityOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + LocationBasedPerformanceTierOperations, + LogFilesOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + RecoverableServersOperations, + ReplicasOperations, + ServerAdministratorsOperations, + ServerBasedPerformanceTierOperations, + ServerKeysOperations, + ServerParametersOperations, + ServerSecurityAlertPoliciesOperations, + ServersOperations, + VirtualNetworkRulesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class PostgreSQLManagementClient: # pylint: disable=too-many-instance-attributes + +class PostgreSQLManagementClient: # 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 PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. @@ -73,9 +92,9 @@ class PostgreSQLManagementClient: # pylint: disable=too-many-instance-attribu azure.mgmt.rdbms.postgresql.aio.operations.PrivateLinkResourcesOperations :ivar server_keys: ServerKeysOperations operations :vartype server_keys: azure.mgmt.rdbms.postgresql.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 @@ -90,37 +109,27 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = PostgreSQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = PostgreSQLManagementClientConfiguration( + 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 ) @@ -136,9 +145,7 @@ 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 ) @@ -148,16 +155,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 @@ -166,7 +166,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/postgresql/aio/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/__init__.py index 8d203af79282..8c27a8a6a8b9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/__init__.py @@ -28,25 +28,26 @@ 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', - 'PrivateEndpointConnectionsOperations', - 'PrivateLinkResourcesOperations', - 'ServerKeysOperations', + "ServersOperations", + "ReplicasOperations", + "FirewallRulesOperations", + "VirtualNetworkRulesOperations", + "DatabasesOperations", + "ConfigurationsOperations", + "ServerParametersOperations", + "LogFilesOperations", + "ServerAdministratorsOperations", + "RecoverableServersOperations", + "ServerBasedPerformanceTierOperations", + "LocationBasedPerformanceTierOperations", + "CheckNameAvailabilityOperations", + "Operations", + "ServerSecurityAlertPoliciesOperations", + "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/postgresql/aio/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_check_name_availability_operations.py index 9981fb1cdd6f..3a61a1be7fa1 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_check_name_availability_operations.py @@ -6,9 +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, Optional, TypeVar - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._check_name_availability_operations import build_execute_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class CheckNameAvailabilityOperations: """ .. warning:: @@ -41,46 +55,94 @@ 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.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -88,22 +150,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.DBforPostgreSQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_configurations_operations.py index 28311598fc21..2ea9a07bd620 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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,10 +30,20 @@ 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 -T = TypeVar('T') +from ...operations._configurations_operations import ( + build_create_or_update_request, + build_get_request, + build_list_by_server_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ConfigurationsOperations: """ .. warning:: @@ -45,38 +63,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: Literal["2017-12-01"] + 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, ) @@ -84,10 +111,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]: @@ -96,38 +122,117 @@ 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.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 + this 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.postgresql.models.Configuration] + :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.postgresql.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.postgresql.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 @@ -139,20 +244,17 @@ 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.postgresql.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, 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: Literal["2017-12-01"] + 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, @@ -161,83 +263,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.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -245,68 +339,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('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.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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) + :return: An iterator like instance of either Configuration or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -314,16 +404,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" @@ -339,10 +420,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 @@ -352,8 +431,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.DBforPostgreSQL/servers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_databases_operations.py index e2268a28762f..041da9e3fe2a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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,10 +30,21 @@ 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, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class DatabasesOperations: """ .. warning:: @@ -45,38 +64,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: Literal["2017-12-01"] + 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 +112,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,41 +123,43 @@ 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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 @@ -142,20 +171,94 @@ 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.postgresql.models.Database] - :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, + 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.postgresql.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.postgresql.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.postgresql.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', "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: Literal["2017-12-01"] + 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, @@ -164,66 +267,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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -231,10 +328,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]: @@ -244,28 +340,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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -276,100 +365,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -377,67 +455,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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -445,16 +519,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" @@ -470,10 +535,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 @@ -483,8 +546,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.DBforPostgreSQL/servers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_firewall_rules_operations.py index ca0b4f8a457b..d7a3e3d82155 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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,10 +30,21 @@ 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, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class FirewallRulesOperations: """ .. warning:: @@ -45,38 +64,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: Literal["2017-12-01"] + 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 +112,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,41 +123,120 @@ 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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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.postgresql.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.postgresql.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 @@ -142,20 +248,17 @@ 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.postgresql.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', "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: Literal["2017-12-01"] + 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, @@ -164,66 +267,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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -231,10 +328,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]: @@ -244,28 +340,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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -276,100 +365,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -377,68 +455,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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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) + :return: An iterator like instance of either FirewallRule or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.models.FirewallRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -446,16 +520,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 +536,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 +547,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.DBforPostgreSQL/servers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_location_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_location_based_performance_tier_operations.py index a5599f71fdbb..f6a8a7102947 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_location_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_location_based_performance_tier_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. # -------------------------------------------------------------------------- +import sys 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 @@ -20,9 +28,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._location_based_performance_tier_operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LocationBasedPerformanceTierOperations: """ .. warning:: @@ -42,45 +56,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.postgresql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -88,15 +98,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" @@ -112,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 @@ -125,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.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_log_files_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_log_files_operations.py index 42d32bbf8a4e..67c17ab44aac 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_log_files_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_log_files_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. # -------------------------------------------------------------------------- +import sys 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 @@ -20,9 +28,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._log_files_operations import build_list_by_server_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LogFilesOperations: """ .. warning:: @@ -42,48 +56,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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -91,16 +102,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" @@ -116,10 +118,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 @@ -129,8 +129,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.DBforPostgreSQL/servers/{serverName}/logFiles"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/logFiles"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_operations.py index 449325e51ba2..2a57b555de34 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class Operations: """ .. warning:: @@ -41,37 +55,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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -79,22 +88,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.DBforPostgreSQL/operations"} # type: ignore - + list.metadata = {"url": "/providers/Microsoft.DBforPostgreSQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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/postgresql/aio/operations/_private_endpoint_connections_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_private_endpoint_connections_operations.py index 3a1eeadfaba2..43fa61506c8a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_private_endpoint_connections_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 +import sys +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,10 +30,22 @@ 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 -T = TypeVar('T') +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, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class PrivateEndpointConnectionsOperations: """ .. warning:: @@ -45,50 +65,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.postgresql.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: Literal["2018-06-01"] + 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, ) @@ -96,49 +111,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + 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, @@ -146,7 +168,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, ) @@ -154,10 +177,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]: @@ -166,38 +188,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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 @@ -210,20 +274,55 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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: Literal["2018-06-01"] + 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, @@ -232,66 +331,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + 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, ) @@ -299,10 +392,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]: @@ -312,28 +404,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -344,88 +429,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: Literal["2018-06-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + 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, ) @@ -433,33 +521,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _update_tags_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -467,17 +555,102 @@ 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.postgresql.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.postgresql.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 + this 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.postgresql.models.PrivateEndpointConnection] + :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.postgresql.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 @@ -490,20 +663,17 @@ async def begin_update_tags( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.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, 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: Literal["2018-06-01"] + 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, @@ -512,82 +682,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_update_tags.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.models.PrivateEndpointConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2018-06-01"] + 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, ) @@ -595,16 +760,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" @@ -620,10 +776,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 @@ -633,8 +787,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_private_link_resources_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_private_link_resources_operations.py index af7decf30777..62bef64c238f 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_private_link_resources_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_private_link_resources_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. # -------------------------------------------------------------------------- +import sys 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 +29,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._private_link_resources_operations import build_get_request, build_list_by_server_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class PrivateLinkResourcesOperations: """ .. warning:: @@ -43,49 +57,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 PostgreSQL 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.postgresql.models.PrivateLinkResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2018-06-01"] + 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, ) @@ -93,16 +104,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" @@ -118,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 @@ -131,55 +131,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.DBforPostgreSQL/servers/{serverName}/privateLinkResources"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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.postgresql.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: Literal["2018-06-01"] + 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, ) @@ -187,22 +181,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.DBforPostgreSQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_recoverable_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_recoverable_servers_operations.py index 24499345c5ce..b7f4e0408e48 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_recoverable_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_recoverable_servers_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._recoverable_servers_operations import build_get_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class RecoverableServersOperations: """ .. warning:: @@ -41,46 +55,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 PostgreSQL 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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -88,22 +96,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.DBforPostgreSQL/servers/{serverName}/recoverableServers"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/recoverableServers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_replicas_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_replicas_operations.py index 90290f5e98cd..8e2a2771bb70 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_replicas_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_replicas_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. # -------------------------------------------------------------------------- +import sys 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 @@ -20,9 +28,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._replicas_operations import build_list_by_server_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReplicasOperations: """ .. warning:: @@ -42,48 +56,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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -91,16 +102,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" @@ -116,10 +118,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 @@ -129,8 +129,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.DBforPostgreSQL/servers/{serverName}/replicas"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/replicas"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_administrators_operations.py index deb126091725..eb758b6a0a1a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_administrators_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_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 +import sys +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,10 +30,21 @@ 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 -T = TypeVar('T') +from ...operations._server_administrators_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerAdministratorsOperations: """ .. warning:: @@ -45,46 +64,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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -92,55 +107,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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -148,10 +171,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]: @@ -159,40 +181,42 @@ 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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 @@ -205,20 +229,93 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.ServerAdministratorResource] - :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, + 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.postgresql.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.postgresql.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 + this 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.postgresql.models.ServerAdministratorResource] + :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: Literal["2017-12-01"] + 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, @@ -226,64 +323,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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -291,10 +383,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]: @@ -304,25 +395,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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -333,98 +416,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.models.ServerAdministratorResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -432,16 +507,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" @@ -457,10 +523,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 @@ -470,8 +534,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.DBforPostgreSQL/servers/{serverName}/administrators"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_based_performance_tier_operations.py index 5f3abbbc3a5f..3aca60a3cb1b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_based_performance_tier_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. # -------------------------------------------------------------------------- +import sys 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 @@ -20,9 +28,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._server_based_performance_tier_operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerBasedPerformanceTierOperations: """ .. warning:: @@ -42,49 +56,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 PostgreSQL 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.postgresql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -92,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" @@ -117,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 @@ -130,8 +131,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.DBforPostgreSQL/servers/{serverName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_keys_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_keys_operations.py index 5faab9ae9e60..268a9d59a8e0 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_keys_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_keys_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 +import sys +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,10 +30,21 @@ 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 -T = TypeVar('T') +from ...operations._server_keys_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerKeysOperations: """ .. warning:: @@ -45,48 +64,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.postgresql.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.postgresql.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: Literal["2020-01-01"] + 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, ) @@ -94,16 +108,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" @@ -119,10 +124,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 +135,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.DBforPostgreSQL/servers/{serverName}/keys"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 PostgreSQL Server key to be retrieved. + :param key_name: The name of the PostgreSQL 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.postgresql.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: Literal["2020-01-01"] + 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, ) @@ -188,57 +183,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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2020-01-01"] + 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, ) @@ -246,10 +249,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]: @@ -257,41 +259,84 @@ 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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 PostgreSQL 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 PostgreSQL Server key resource state. + :param parameters: The requested PostgreSQL Server key resource state. Required. :type parameters: ~azure.mgmt.rdbms.postgresql.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 + this 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.postgresql.models.ServerKey] + :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 PostgreSQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the PostgreSQL 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 PostgreSQL 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 @@ -303,20 +348,56 @@ 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.postgresql.models.ServerKey] - :raises: ~azure.core.exceptions.HttpResponseError + :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 PostgreSQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the PostgreSQL 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 PostgreSQL Server key resource state. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.postgresql.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.postgresql.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: Literal["2020-01-01"] + 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, @@ -325,66 +406,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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2020-01-01"] + 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, ) @@ -392,10 +467,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]: @@ -405,28 +479,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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 PostgreSQL Server key to be deleted. + :param key_name: The name of the PostgreSQL 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 @@ -437,53 +504,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: Literal["2020-01-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore 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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_parameters_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_parameters_operations.py index d4d0a2ae96a9..f093d1ae896d 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_parameters_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_parameters_operations.py @@ -6,9 +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, Optional, TypeVar, Union, cast +import sys +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,10 +28,16 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._server_parameters_operations import build_list_update_configurations_request_initial -T = TypeVar('T') +from ...operations._server_parameters_operations import build_list_update_configurations_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerParametersOperations: """ .. warning:: @@ -43,36 +57,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: Literal["2017-12-01"] + 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, ) @@ -80,10 +103,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]: @@ -92,35 +114,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.DBforPostgreSQL/servers/{serverName}/updateConfigurations"} # type: ignore - + _list_update_configurations_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 @@ -133,20 +157,90 @@ async def begin_list_update_configurations( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, @@ -154,36 +248,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.DBforPostgreSQL/servers/{serverName}/updateConfigurations"} # type: ignore + begin_list_update_configurations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/updateConfigurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_security_alert_policies_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_security_alert_policies_operations.py index 0dfab384b880..83246eff038d 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_security_alert_policies_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_server_security_alert_policies_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 +import sys +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,10 +30,20 @@ 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 -T = TypeVar('T') +from ...operations._server_security_alert_policies_operations import ( + build_create_or_update_request, + build_get_request, + build_list_by_server_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerSecurityAlertPoliciesOperations: """ .. warning:: @@ -45,51 +63,50 @@ 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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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 +114,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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +171,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 +180,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,39 +191,122 @@ 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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.models.SecurityAlertPolicyName - :param parameters: The server security alert policy. + :param parameters: The server security alert policy. Required. :type parameters: ~azure.mgmt.rdbms.postgresql.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 + this 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.postgresql.models.ServerSecurityAlertPolicy] + :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.postgresql.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.postgresql.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.postgresql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.rdbms.postgresql.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 @@ -212,20 +319,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicy] - :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.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: Literal["2017-12-01"] + 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, @@ -234,82 +338,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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.models.ServerSecurityAlertPolicyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -317,16 +416,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" @@ -342,10 +432,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 @@ -355,8 +443,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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_servers_operations.py index c16ddf694549..36c2541e7cab 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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,10 +30,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_update_request_initial -T = TypeVar('T') +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_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServersOperations: """ .. warning:: @@ -45,36 +67,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: Literal["2017-12-01"] + 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, ) @@ -82,10 +109,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,38 +120,107 @@ 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.DBforPostgreSQL/servers/{serverName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 will overwrite an 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.postgresql.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.postgresql.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 will overwrite an 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.postgresql.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 will overwrite an 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.postgresql.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 @@ -137,20 +232,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.postgresql.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: Literal["2017-12-01"] + 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, @@ -158,69 +250,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -228,10 +326,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]: @@ -240,36 +337,111 @@ 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.DBforPostgreSQL/servers/{serverName}"} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 + this 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.postgresql.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 + this 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.postgresql.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.postgresql.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 @@ -281,20 +453,17 @@ 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.postgresql.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: Literal["2017-12-01"] + 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, @@ -302,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -367,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]: @@ -380,25 +543,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -409,95 +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', "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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -505,63 +648,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -569,15 +707,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" @@ -593,10 +723,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 @@ -606,45 +734,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.DBforPostgreSQL/servers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -652,14 +775,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" @@ -675,10 +791,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 @@ -688,36 +802,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.DBforPostgreSQL/servers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -725,10 +836,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]: @@ -738,25 +848,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.DBforPostgreSQL/servers/{serverName}/restart"} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -767,52 +869,45 @@ 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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._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.DBforPostgreSQL/servers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/restart"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_virtual_network_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_virtual_network_rules_operations.py index 6f0b75ac7e6d..e849707431a0 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_virtual_network_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/aio/operations/_virtual_network_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 +import sys +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,10 +30,21 @@ 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 -T = TypeVar('T') +from ...operations._virtual_network_rules_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class VirtualNetworkRulesOperations: """ .. warning:: @@ -45,50 +64,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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -96,57 +110,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -154,10 +176,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]: @@ -166,41 +187,122 @@ 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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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 + this 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.postgresql.models.VirtualNetworkRule] + :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.postgresql.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 @@ -213,20 +315,17 @@ async def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql.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, 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: Literal["2017-12-01"] + 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 +334,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +395,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 +407,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +432,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.models.VirtualNetworkRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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 +523,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 +539,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 +550,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/__init__.py index 4a22d7586177..5aab218cf147 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/__init__.py @@ -60,104 +60,102 @@ from ._models_py3 import VirtualNetworkRule from ._models_py3 import VirtualNetworkRuleListResult - -from ._postgre_sql_management_client_enums import ( - CreateMode, - GeoRedundantBackup, - IdentityType, - InfrastructureEncryption, - MinimalTlsVersionEnum, - OperationOrigin, - PrivateEndpointProvisioningState, - PrivateLinkServiceConnectionStateActionsRequire, - PrivateLinkServiceConnectionStateStatus, - PublicNetworkAccessEnum, - SecurityAlertPolicyName, - ServerKeyType, - ServerSecurityAlertPolicyState, - ServerState, - ServerVersion, - SkuTier, - SslEnforcementEnum, - StorageAutogrow, - VirtualNetworkRuleState, -) +from ._postgre_sql_management_client_enums import CreateMode +from ._postgre_sql_management_client_enums import GeoRedundantBackup +from ._postgre_sql_management_client_enums import IdentityType +from ._postgre_sql_management_client_enums import InfrastructureEncryption +from ._postgre_sql_management_client_enums import MinimalTlsVersionEnum +from ._postgre_sql_management_client_enums import OperationOrigin +from ._postgre_sql_management_client_enums import PrivateEndpointProvisioningState +from ._postgre_sql_management_client_enums import PrivateLinkServiceConnectionStateActionsRequire +from ._postgre_sql_management_client_enums import PrivateLinkServiceConnectionStateStatus +from ._postgre_sql_management_client_enums import PublicNetworkAccessEnum +from ._postgre_sql_management_client_enums import SecurityAlertPolicyName +from ._postgre_sql_management_client_enums import ServerKeyType +from ._postgre_sql_management_client_enums import ServerSecurityAlertPolicyState +from ._postgre_sql_management_client_enums import ServerState +from ._postgre_sql_management_client_enums import ServerVersion +from ._postgre_sql_management_client_enums import SkuTier +from ._postgre_sql_management_client_enums import SslEnforcementEnum +from ._postgre_sql_management_client_enums import StorageAutogrow +from ._postgre_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__ = [ - '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', - 'RecoverableServerResource', - 'Resource', - 'ResourceIdentity', - 'Server', - 'ServerAdministratorResource', - 'ServerAdministratorResourceListResult', - 'ServerForCreate', - 'ServerKey', - 'ServerKeyListResult', - 'ServerListResult', - 'ServerPrivateEndpointConnection', - 'ServerPrivateEndpointConnectionProperties', - 'ServerPrivateLinkServiceConnectionStateProperty', - 'ServerPropertiesForCreate', - 'ServerPropertiesForDefaultCreate', - 'ServerPropertiesForGeoRestore', - 'ServerPropertiesForReplica', - 'ServerPropertiesForRestore', - 'ServerSecurityAlertPolicy', - 'ServerSecurityAlertPolicyListResult', - 'ServerUpdateParameters', - 'Sku', - 'StorageProfile', - 'TagsObject', - 'TrackedResource', - 'VirtualNetworkRule', - 'VirtualNetworkRuleListResult', - 'CreateMode', - 'GeoRedundantBackup', - 'IdentityType', - 'InfrastructureEncryption', - 'MinimalTlsVersionEnum', - 'OperationOrigin', - 'PrivateEndpointProvisioningState', - 'PrivateLinkServiceConnectionStateActionsRequire', - 'PrivateLinkServiceConnectionStateStatus', - 'PublicNetworkAccessEnum', - 'SecurityAlertPolicyName', - 'ServerKeyType', - 'ServerSecurityAlertPolicyState', - 'ServerState', - 'ServerVersion', - 'SkuTier', - 'SslEnforcementEnum', - 'StorageAutogrow', - 'VirtualNetworkRuleState', + "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", + "RecoverableServerResource", + "Resource", + "ResourceIdentity", + "Server", + "ServerAdministratorResource", + "ServerAdministratorResourceListResult", + "ServerForCreate", + "ServerKey", + "ServerKeyListResult", + "ServerListResult", + "ServerPrivateEndpointConnection", + "ServerPrivateEndpointConnectionProperties", + "ServerPrivateLinkServiceConnectionStateProperty", + "ServerPropertiesForCreate", + "ServerPropertiesForDefaultCreate", + "ServerPropertiesForGeoRestore", + "ServerPropertiesForReplica", + "ServerPropertiesForRestore", + "ServerSecurityAlertPolicy", + "ServerSecurityAlertPolicyListResult", + "ServerUpdateParameters", + "Sku", + "StorageProfile", + "TagsObject", + "TrackedResource", + "VirtualNetworkRule", + "VirtualNetworkRuleListResult", + "CreateMode", + "GeoRedundantBackup", + "IdentityType", + "InfrastructureEncryption", + "MinimalTlsVersionEnum", + "OperationOrigin", + "PrivateEndpointProvisioningState", + "PrivateLinkServiceConnectionStateActionsRequire", + "PrivateLinkServiceConnectionStateStatus", + "PublicNetworkAccessEnum", + "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/postgresql/models/_models_py3.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_models_py3.py index 5b43750f91f6..84f5668a38b7 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_models_py3.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from .. import _serialization + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - import __init__ as _models + from .. import models as _models -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. @@ -32,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 @@ -71,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 Configuration(ProxyResource): @@ -119,41 +118,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 @@ -162,7 +155,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. @@ -170,20 +163,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.postgresql.models.Configuration] """ - super(ConfigurationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value @@ -207,38 +195,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. @@ -246,24 +228,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.postgresql.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. @@ -271,31 +248,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. @@ -313,28 +286,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 @@ -357,51 +326,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. @@ -409,20 +378,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.postgresql.models.FirewallRule] """ - super(FirewallRuleListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value @@ -440,7 +404,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. @@ -452,22 +416,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__( @@ -480,13 +444,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 @@ -494,7 +458,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. @@ -502,24 +466,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.postgresql.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. @@ -531,9 +490,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__( @@ -552,51 +511,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. @@ -606,40 +559,36 @@ class Operation(msrest.serialization.Model): :ivar display: The localized display information for this particular operation or action. :vartype display: ~azure.mgmt.rdbms.postgresql.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.postgresql.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. @@ -655,33 +604,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. @@ -689,24 +634,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.postgresql.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. @@ -714,24 +654,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.postgresql.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. @@ -756,20 +691,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, @@ -801,7 +739,7 @@ def __init__( :paramtype service_level_objectives: list[~azure.mgmt.rdbms.postgresql.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 @@ -812,7 +750,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. @@ -836,20 +774,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, @@ -879,7 +817,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 @@ -914,19 +852,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__( @@ -944,13 +885,13 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.rdbms.postgresql.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. @@ -962,27 +903,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. @@ -990,20 +927,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 @@ -1025,30 +957,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. @@ -1060,27 +988,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. @@ -1092,67 +1016,57 @@ 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 @@ -1186,36 +1100,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}, + "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": {"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 @@ -1224,7 +1134,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. @@ -1232,37 +1142,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.postgresql.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.postgresql.models.IdentityType """ - super(ResourceIdentity, self).__init__(**kwargs) + super().__init__(**kwargs) self.principal_id = None self.type = type self.tenant_id = None @@ -1283,46 +1186,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. @@ -1337,9 +1234,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.postgresql.models.ResourceIdentity @@ -1348,23 +1245,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: "9.5", "9.6", "10", "10.0", "10.2", "11". + :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.ServerState :ivar fully_qualified_domain_name: The fully qualified domain name of a server. :vartype fully_qualified_domain_name: str @@ -1380,7 +1277,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.postgresql.models.PublicNetworkAccessEnum :ivar private_endpoint_connections: List of private endpoint connections on a server. @@ -1389,38 +1286,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}, + "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": {"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__( @@ -1446,9 +1346,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.postgresql.models.ResourceIdentity @@ -1457,21 +1357,22 @@ 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: "9.5", "9.6", "10", "10.0", "10.2", "11". + :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and + "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.ServerState :keyword fully_qualified_domain_name: The fully qualified domain name of a server. :paramtype fully_qualified_domain_name: str @@ -1487,11 +1388,11 @@ 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.postgresql.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 @@ -1524,8 +1425,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 @@ -1536,33 +1436,32 @@ 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__( self, *, - administrator_type: Optional[str] = None, + administrator_type: Optional[Literal["ActiveDirectory"]] = None, login: Optional[str] = None, sid: Optional[str] = None, tenant_id: Optional[str] = None, **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 @@ -1571,14 +1470,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. @@ -1586,24 +1485,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.postgresql.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. @@ -1612,25 +1506,25 @@ class ServerForCreate(msrest.serialization.Model): :vartype identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity :ivar sku: The SKU (pricing tier) of the server. :vartype sku: ~azure.mgmt.rdbms.postgresql.models.Sku - :ivar properties: Required. Properties of the server. + :ivar properties: Properties of the server. Required. :vartype properties: ~azure.mgmt.rdbms.postgresql.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__( @@ -1648,14 +1542,14 @@ def __init__( :paramtype identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity :keyword sku: The SKU (pricing tier) of the server. :paramtype sku: ~azure.mgmt.rdbms.postgresql.models.Sku - :keyword properties: Required. Properties of the server. + :keyword properties: Properties of the server. Required. :paramtype properties: ~azure.mgmt.rdbms.postgresql.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 @@ -1678,7 +1572,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.postgresql.models.ServerKeyType :ivar uri: The URI of the key. :vartype uri: str @@ -1687,21 +1581,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__( @@ -1712,19 +1606,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.postgresql.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 PostgreSQL Server keys. Variables are only populated by the server, and will be ignored when sending a request. @@ -1736,27 +1630,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. @@ -1764,24 +1654,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.postgresql.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. @@ -1794,27 +1679,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. @@ -1826,26 +1707,31 @@ class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): :vartype private_link_service_connection_state: ~azure.mgmt.rdbms.postgresql.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.postgresql.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 ): """ @@ -1856,112 +1742,113 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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: "9.5", "9.6", "10", "10.0", "10.2", "11". + :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.postgresql.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.postgresql.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__( @@ -1976,28 +1863,29 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and + "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.postgresql.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 @@ -2012,51 +1900,51 @@ class ServerPropertiesForDefaultCreate(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.postgresql.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.postgresql.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). + :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). 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__( @@ -2073,34 +1961,43 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and + "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.postgresql.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). + :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). 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 @@ -2110,46 +2007,46 @@ class ServerPropertiesForGeoRestore(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.postgresql.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.postgresql.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__( @@ -2165,31 +2062,40 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and + "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.postgresql.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 @@ -2198,46 +2104,46 @@ class ServerPropertiesForReplica(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.postgresql.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.postgresql.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__( @@ -2253,31 +2159,40 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and + "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.postgresql.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 @@ -2286,51 +2201,51 @@ class ServerPropertiesForRestore(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :ivar version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.postgresql.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.postgresql.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__( @@ -2347,34 +2262,43 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", "11". + :keyword version: Server version. Known values are: "9.5", "9.6", "10", "10.0", "10.2", and + "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.postgresql.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 @@ -2393,7 +2317,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.postgresql.models.ServerSecurityAlertPolicyState :ivar disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. @@ -2414,22 +2338,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__( @@ -2446,7 +2370,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.postgresql.models.ServerSecurityAlertPolicyState :keyword disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. @@ -2466,7 +2390,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 @@ -2476,7 +2400,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. @@ -2488,51 +2412,47 @@ 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.postgresql.models.ResourceIdentity :ivar sku: The SKU (pricing tier) of the server. :vartype sku: ~azure.mgmt.rdbms.postgresql.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.postgresql.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: "9.5", "9.6", "10", "10.0", "10.2", - "11". + and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.models.PublicNetworkAccessEnum :ivar replication_role: The replication role of the server. @@ -2540,16 +2460,16 @@ class ServerUpdateParameters(msrest.serialization.Model): """ _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__( @@ -2572,31 +2492,31 @@ def __init__( :paramtype identity: ~azure.mgmt.rdbms.postgresql.models.ResourceIdentity :keyword sku: The SKU (pricing tier) of the server. :paramtype sku: ~azure.mgmt.rdbms.postgresql.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.postgresql.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: "9.5", "9.6", "10", "10.0", - "10.2", "11". + "10.2", and "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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 @@ -2609,16 +2529,16 @@ def __init__( self.replication_role = replication_role -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.postgresql.models.SkuTier :ivar capacity: The scale up/out capacity, representing server's compute units. :vartype capacity: int @@ -2629,16 +2549,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__( @@ -2652,11 +2572,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.postgresql.models.SkuTier :keyword capacity: The scale up/out capacity, representing server's compute units. :paramtype capacity: int @@ -2665,7 +2585,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 @@ -2673,25 +2593,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.postgresql.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.postgresql.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__( @@ -2707,42 +2627,38 @@ 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.postgresql.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.postgresql.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 @@ -2765,24 +2681,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.postgresql.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__( @@ -2799,13 +2715,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. @@ -2817,21 +2733,17 @@ 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 diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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/postgresql/models/_postgre_sql_management_client_enums.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_postgre_sql_management_client_enums.py index f262ba79d605..c8bad2807ea2 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_postgre_sql_management_client_enums.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/_postgre_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,58 +72,61 @@ 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 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.""" NINE5 = "9.5" NINE6 = "9.6" @@ -131,31 +135,31 @@ class ServerVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): TEN2 = "10.2" ELEVEN = "11" + 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/postgresql/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/__init__.py index 8d203af79282..8c27a8a6a8b9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/__init__.py @@ -28,25 +28,26 @@ 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', - 'PrivateEndpointConnectionsOperations', - 'PrivateLinkResourcesOperations', - 'ServerKeysOperations', + "ServersOperations", + "ReplicasOperations", + "FirewallRulesOperations", + "VirtualNetworkRulesOperations", + "DatabasesOperations", + "ConfigurationsOperations", + "ServerParametersOperations", + "LogFilesOperations", + "ServerAdministratorsOperations", + "RecoverableServersOperations", + "ServerBasedPerformanceTierOperations", + "LocationBasedPerformanceTierOperations", + "CheckNameAvailabilityOperations", + "Operations", + "ServerSecurityAlertPoliciesOperations", + "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/postgresql/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_check_name_availability_operations.py index 43f3be18c153..5d80ebde7c6e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_check_name_availability_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, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, 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 +25,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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability" + ) # pylint: disable=line-too-long 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 +87,94 @@ 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.postgresql.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.postgresql.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.postgresql.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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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 +182,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.DBforPostgreSQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_configurations_operations.py index 634ae5d63fa2..f11fbae53bbe 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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 +28,123 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +165,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: Literal["2017-12-01"] + 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 +213,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 +224,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.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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.postgresql.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.postgresql.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 +346,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.postgresql.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: Literal["2017-12-01"] + 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 +365,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.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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,68 +441,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.DBforPostgreSQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -439,16 +505,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" @@ -464,10 +521,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 +532,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.DBforPostgreSQL/servers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/configurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_databases_operations.py index 3ba196f1463c..1e84e87addde 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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 +28,157 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +199,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: Literal["2017-12-01"] + 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 +247,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 +258,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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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.postgresql.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.postgresql.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 +380,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.postgresql.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: Literal["2017-12-01"] + 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 +399,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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +460,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 +472,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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +497,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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 +585,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.DBforPostgreSQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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 +647,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 +663,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 +674,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.DBforPostgreSQL/servers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_firewall_rules_operations.py index 221d9d716d73..b9ad87b4255f 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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 +28,157 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +199,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: Literal["2017-12-01"] + 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 +247,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 +258,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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 +306,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.postgresql.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.postgresql.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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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 +402,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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +463,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 +475,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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +500,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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,68 +590,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.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -610,16 +654,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" @@ -635,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 @@ -648,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.DBforPostgreSQL/servers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_location_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_location_based_performance_tier_operations.py index fa8261787f8a..bd36552c90f3 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_location_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_location_based_performance_tier_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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,47 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - 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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/performanceTiers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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,45 +87,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.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.postgresql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -126,15 +129,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" @@ -150,10 +145,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 @@ -163,8 +156,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.DBforPostgreSQL/locations/{locationName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_log_files_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_log_files_operations.py index 58ab04babcf6..03cd319f3012 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_log_files_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_log_files_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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,52 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/logFiles") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +92,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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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 +136,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 +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 @@ -168,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_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/logFiles"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/logFiles"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_operations.py index d7aaef88d490..bb32d236b8b7 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,38 +25,38 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: + +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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DBforPostgreSQL/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 +77,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.postgresql.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: Literal["2017-12-01"] + 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 +110,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.DBforPostgreSQL/operations"} # type: ignore - + list.metadata = {"url": "/providers/Microsoft.DBforPostgreSQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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/postgresql/operations/_private_endpoint_connections_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_private_endpoint_connections_operations.py index f7d1fd50af48..2c62fa2d3145 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_private_endpoint_connections_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_private_endpoint_connections_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 +import sys +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 +28,20 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( resource_group_name: str, server_name: str, @@ -39,83 +52,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: Literal["2018-06-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +135,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: Literal["2018-06-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +260,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.postgresql.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: Literal["2018-06-01"] + 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 +306,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + 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 +363,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 +372,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 +383,118 @@ 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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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 + 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.postgresql.models.PrivateEndpointConnection] + :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.postgresql.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 @@ -421,20 +507,17 @@ def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.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: Literal["2018-06-01"] + 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, @@ -443,66 +526,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + 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, ) @@ -510,10 +587,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]: @@ -523,28 +599,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -555,88 +624,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: Literal["2018-06-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + 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, ) @@ -644,33 +716,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + _update_tags_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -678,17 +750,102 @@ 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.postgresql.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.postgresql.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.postgresql.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.postgresql.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 @@ -701,20 +858,17 @@ def begin_update_tags( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.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: Literal["2018-06-01"] + 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, @@ -723,82 +877,77 @@ 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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_update_tags.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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) + :return: An iterator like instance of either PrivateEndpointConnection or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2018-06-01"] + 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, ) @@ -806,16 +955,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" @@ -831,10 +971,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 @@ -844,8 +982,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.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateEndpointConnections"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_private_link_resources_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_private_link_resources_operations.py index c9a6181b676b..8db0777ace78 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_private_link_resources_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_private_link_resources_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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 +26,86 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_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: Literal["2018-06-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2018-06-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources/{groupName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +126,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 PostgreSQL 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.postgresql.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.postgresql.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: Literal["2018-06-01"] + 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 +172,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 +188,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 +199,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.DBforPostgreSQL/servers/{serverName}/privateLinkResources"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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.postgresql.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: Literal["2018-06-01"] + 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 +249,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.DBforPostgreSQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_recoverable_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_recoverable_servers_operations.py index d1a08c67a1eb..7199a0074cab 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_recoverable_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_recoverable_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,48 +25,50 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/recoverableServers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +89,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 PostgreSQL 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.postgresql.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: Literal["2017-12-01"] + 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 +130,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.DBforPostgreSQL/servers/{serverName}/recoverableServers"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/recoverableServers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_replicas_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_replicas_operations.py index 0decd97e6c6f..0bb13ecf5c8b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_replicas_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_replicas_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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,52 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/replicas") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +92,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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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 +136,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 +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 @@ -168,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_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/replicas"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/replicas"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_administrators_operations.py index cfb769657681..c2e583089fbe 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_administrators_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_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 +import sys +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 +28,150 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - 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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +192,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.postgresql.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: Literal["2017-12-01"] + 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 +233,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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +297,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 +307,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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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.postgresql.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.postgresql.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 +431,17 @@ def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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 +449,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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +509,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 +521,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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +542,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.models.ServerAdministratorResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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 +633,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 +649,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 +660,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.DBforPostgreSQL/servers/{serverName}/administrators"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_based_performance_tier_operations.py index 50bace99543c..42e6e0589e56 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_based_performance_tier_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +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,50 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - resource_group_name: str, - 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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/performanceTiers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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,49 +90,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") - @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 PostgreSQL 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.postgresql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -132,16 +138,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" @@ -157,10 +154,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 +165,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.DBforPostgreSQL/servers/{serverName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_keys_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_keys_operations.py index 78ab9785aa1f..a6c41522f81b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_keys_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_keys_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 +import sys +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 +28,155 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - resource_group_name: str, - 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: Literal["2020-01-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2020-01-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2020-01-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2020-01-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +197,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.postgresql.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.postgresql.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: Literal["2020-01-01"] + 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 +241,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 +257,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 +268,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.DBforPostgreSQL/servers/{serverName}/keys"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 PostgreSQL Server key to be retrieved. + :param key_name: The name of the PostgreSQL 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.postgresql.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: Literal["2020-01-01"] + 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 +316,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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2020-01-01"] + 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 +382,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 +392,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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 PostgreSQL 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 PostgreSQL Server key resource state. + :param parameters: The requested PostgreSQL Server key resource state. Required. :type parameters: ~azure.mgmt.rdbms.postgresql.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 +440,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.postgresql.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 PostgreSQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the PostgreSQL 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 PostgreSQL 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.postgresql.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 PostgreSQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the PostgreSQL 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 PostgreSQL Server key resource state. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.postgresql.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.postgresql.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: Literal["2020-01-01"] + 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 +536,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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2020-01-01"] + 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 +597,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 +609,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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 PostgreSQL Server key to be deleted. + :param key_name: The name of the PostgreSQL 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 +632,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: Literal["2020-01-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore 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.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/keys/{keyName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_parameters_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_parameters_operations.py index 5a5a43adfd39..95a753476dcd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_parameters_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_parameters_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, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod @@ -21,56 +27,55 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/updateConfigurations") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +96,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: Literal["2017-12-01"] + 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 +142,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 +153,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.DBforPostgreSQL/servers/{serverName}/updateConfigurations"} # type: ignore + _list_update_configurations_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 @@ -181,20 +196,90 @@ def begin_list_update_configurations( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, @@ -202,36 +287,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.DBforPostgreSQL/servers/{serverName}/updateConfigurations"} # type: ignore + begin_list_update_configurations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/updateConfigurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_security_alert_policies_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_security_alert_policies_operations.py index c2b59f7dc50b..73a4d7f0c0a5 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_security_alert_policies_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_server_security_alert_policies_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 +import sys +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 +28,131 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( resource_group_name: str, 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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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,51 +173,50 @@ 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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -222,49 +224,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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, @@ -272,7 +281,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, ) @@ -280,10 +290,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]: @@ -292,39 +301,82 @@ 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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.models.SecurityAlertPolicyName - :param parameters: The server security alert policy. + :param parameters: The server security alert policy. Required. :type parameters: ~azure.mgmt.rdbms.postgresql.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.postgresql.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.postgresql.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 @@ -337,20 +389,57 @@ def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql.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.postgresql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.rdbms.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, @@ -359,82 +448,77 @@ 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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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) + :return: An iterator like instance of either ServerSecurityAlertPolicy or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.models.ServerSecurityAlertPolicyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -442,16 +526,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" @@ -467,10 +542,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 @@ -480,8 +553,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.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_servers_operations.py index fad9e0702a38..d2cce7ea5dd0 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/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 +import sys +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,280 +28,242 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/restart") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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') + _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: """ @@ -316,36 +284,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: Literal["2017-12-01"] + 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, ) @@ -353,10 +326,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]: @@ -365,38 +337,105 @@ 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.DBforPostgreSQL/servers/{serverName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 will overwrite an 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.postgresql.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.postgresql.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 will overwrite an 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.postgresql.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 will overwrite an 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.postgresql.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 @@ -407,20 +446,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.postgresql.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: Literal["2017-12-01"] + 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, @@ -428,69 +464,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -498,10 +540,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]: @@ -510,36 +551,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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 @@ -550,20 +593,88 @@ 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.postgresql.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.postgresql.models.Server] + :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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, @@ -571,64 +682,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -636,10 +742,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]: @@ -649,25 +754,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -678,95 +775,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -774,62 +859,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.DBforPostgreSQL/servers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -837,15 +918,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" @@ -861,10 +934,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 @@ -874,44 +945,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.DBforPostgreSQL/servers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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, ) @@ -919,14 +986,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" @@ -942,10 +1002,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 @@ -955,36 +1013,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.DBforPostgreSQL/servers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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, ) @@ -992,10 +1047,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]: @@ -1005,25 +1059,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.DBforPostgreSQL/servers/{serverName}/restart"} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 @@ -1034,52 +1080,45 @@ 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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._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.DBforPostgreSQL/servers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/restart"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_virtual_network_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_virtual_network_rules_operations.py index 3410e2bd961f..c40aebcb595b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_virtual_network_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/operations/_virtual_network_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 +import sys +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 +28,151 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - resource_group_name: str, - 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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +193,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.postgresql.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: Literal["2017-12-01"] + 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 +239,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +305,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 +316,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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.postgresql.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.postgresql.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 +441,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.postgresql.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: Literal["2017-12-01"] + 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 +460,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Literal["2017-12-01"] + 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 +521,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 +533,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +558,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: Literal["2017-12-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, 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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql.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.postgresql.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: Literal["2017-12-01"] + 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 +648,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 +664,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 +675,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.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/virtualNetworkRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/__init__.py index 64e2cc211b0f..473b3c5678d9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/__init__.py @@ -17,7 +17,10 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['PostgreSQLManagementClient'] + +__all__ = [ + "PostgreSQLManagementClient", +] __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/postgresql_flexibleservers/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_configuration.py index ae1d833395d7..e8f3d2ca05cd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential @@ -25,23 +31,18 @@ class PostgreSQLManagementClientConfiguration(Configuration): # pylint: disable 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 "2022-01-20-preview". Note that overriding + :keyword api_version: Api Version. Default value is "2022-03-08-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(PostgreSQLManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2022-01-20-preview") # type: str + api_version = kwargs.pop("api_version", "2022-03-08-preview") # type: Literal["2022-03-08-preview"] if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +52,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/postgresql_flexibleservers/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_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/postgresql_flexibleservers/_postgre_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_postgre_sql_management_client.py index 17eef297f439..7634de653637 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_postgre_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_postgre_sql_management_client.py @@ -9,57 +9,77 @@ 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 PostgreSQLManagementClientConfiguration -from .operations import BackupsOperations, CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, GetPrivateDnsZoneSuffixOperations, LocationBasedCapabilitiesOperations, Operations, ServersOperations, VirtualNetworkSubnetUsageOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + AdministratorsOperations, + BackupsOperations, + CheckNameAvailabilityOperations, + CheckNameAvailabilityWithLocationOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + GetPrivateDnsZoneSuffixOperations, + LocationBasedCapabilitiesOperations, + Operations, + ServersOperations, + VirtualNetworkSubnetUsageOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class PostgreSQLManagementClient: # pylint: disable=too-many-instance-attributes + +class PostgreSQLManagementClient: # 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 PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. - :ivar databases: DatabasesOperations operations - :vartype databases: azure.mgmt.rdbms.postgresql_flexibleservers.operations.DatabasesOperations - :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations - :vartype get_private_dns_zone_suffix: - azure.mgmt.rdbms.postgresql_flexibleservers.operations.GetPrivateDnsZoneSuffixOperations - :ivar servers: ServersOperations operations - :vartype servers: azure.mgmt.rdbms.postgresql_flexibleservers.operations.ServersOperations + :ivar administrators: AdministratorsOperations operations + :vartype administrators: + azure.mgmt.rdbms.postgresql_flexibleservers.operations.AdministratorsOperations :ivar backups: BackupsOperations operations :vartype backups: azure.mgmt.rdbms.postgresql_flexibleservers.operations.BackupsOperations - :ivar firewall_rules: FirewallRulesOperations operations - :vartype firewall_rules: - azure.mgmt.rdbms.postgresql_flexibleservers.operations.FirewallRulesOperations - :ivar configurations: ConfigurationsOperations operations - :vartype configurations: - azure.mgmt.rdbms.postgresql_flexibleservers.operations.ConfigurationsOperations - :ivar check_name_availability: CheckNameAvailabilityOperations operations - :vartype check_name_availability: - azure.mgmt.rdbms.postgresql_flexibleservers.operations.CheckNameAvailabilityOperations :ivar location_based_capabilities: LocationBasedCapabilitiesOperations operations :vartype location_based_capabilities: azure.mgmt.rdbms.postgresql_flexibleservers.operations.LocationBasedCapabilitiesOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: + azure.mgmt.rdbms.postgresql_flexibleservers.operations.CheckNameAvailabilityOperations + :ivar check_name_availability_with_location: CheckNameAvailabilityWithLocationOperations + operations + :vartype check_name_availability_with_location: + azure.mgmt.rdbms.postgresql_flexibleservers.operations.CheckNameAvailabilityWithLocationOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: + azure.mgmt.rdbms.postgresql_flexibleservers.operations.ConfigurationsOperations + :ivar databases: DatabasesOperations operations + :vartype databases: azure.mgmt.rdbms.postgresql_flexibleservers.operations.DatabasesOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: + azure.mgmt.rdbms.postgresql_flexibleservers.operations.FirewallRulesOperations + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.postgresql_flexibleservers.operations.ServersOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.postgresql_flexibleservers.operations.Operations + :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations + :vartype get_private_dns_zone_suffix: + azure.mgmt.rdbms.postgresql_flexibleservers.operations.GetPrivateDnsZoneSuffixOperations :ivar virtual_network_subnet_usage: VirtualNetworkSubnetUsageOperations operations :vartype virtual_network_subnet_usage: azure.mgmt.rdbms.postgresql_flexibleservers.operations.VirtualNetworkSubnetUsageOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.rdbms.postgresql_flexibleservers.operations.Operations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The 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 - :keyword api_version: Api Version. Default value is "2022-01-20-preview". Note that overriding + :keyword api_version: Api Version. Default value is "2022-03-08-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no @@ -73,50 +93,39 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = PostgreSQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = PostgreSQLManagementClientConfiguration( + 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.databases = DatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.servers = ServersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.backups = BackupsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.firewall_rules = FirewallRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.configurations = ConfigurationsOperations( + self.administrators = AdministratorsOperations(self._client, self._config, self._serialize, self._deserialize) + self.backups = BackupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_capabilities = LocationBasedCapabilitiesOperations( self._client, self._config, self._serialize, self._deserialize ) self.check_name_availability = CheckNameAvailabilityOperations( self._client, self._config, self._serialize, self._deserialize ) - self.location_based_capabilities = LocationBasedCapabilitiesOperations( + self.check_name_availability_with_location = CheckNameAvailabilityWithLocationOperations( self._client, self._config, self._serialize, self._deserialize ) - self.virtual_network_subnet_usage = VirtualNetworkSubnetUsageOperations( + 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.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( self._client, self._config, self._serialize, self._deserialize ) - self.operations = Operations( + self.virtual_network_subnet_usage = VirtualNetworkSubnetUsageOperations( 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 @@ -125,7 +134,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/postgresql_flexibleservers/_serialization.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_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/postgresql_flexibleservers/_vendor.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_vendor.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_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/postgresql_flexibleservers/_version.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_version.py index a172f504a7eb..e5754a47ce68 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/_version.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_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/postgresql_flexibleservers/aio/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/__init__.py index 6d35026eff99..a3ea1a85dcd9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/__init__.py @@ -14,7 +14,10 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['PostgreSQLManagementClient'] + +__all__ = [ + "PostgreSQLManagementClient", +] __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/postgresql_flexibleservers/aio/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_configuration.py index c28b2c96a5be..e597f50533d7 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential @@ -25,23 +31,18 @@ class PostgreSQLManagementClientConfiguration(Configuration): # pylint: disable 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 "2022-01-20-preview". Note that overriding + :keyword api_version: Api Version. Default value is "2022-03-08-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(PostgreSQLManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2022-01-20-preview") # type: str + api_version = kwargs.pop("api_version", "2022-03-08-preview") # type: Literal["2022-03-08-preview"] if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-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/postgresql_flexibleservers/aio/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_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/postgresql_flexibleservers/aio/_postgre_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_postgre_sql_management_client.py index 77552d418950..b793ff700b83 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_postgre_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/_postgre_sql_management_client.py @@ -9,58 +9,78 @@ 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 PostgreSQLManagementClientConfiguration -from .operations import BackupsOperations, CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, GetPrivateDnsZoneSuffixOperations, LocationBasedCapabilitiesOperations, Operations, ServersOperations, VirtualNetworkSubnetUsageOperations +from .operations import ( + AdministratorsOperations, + BackupsOperations, + CheckNameAvailabilityOperations, + CheckNameAvailabilityWithLocationOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + GetPrivateDnsZoneSuffixOperations, + LocationBasedCapabilitiesOperations, + Operations, + ServersOperations, + VirtualNetworkSubnetUsageOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class PostgreSQLManagementClient: # pylint: disable=too-many-instance-attributes + +class PostgreSQLManagementClient: # 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 PostgreSQL resources including servers, databases, firewall rules, VNET rules, security alert policies, log files and configurations with new business model. + :ivar administrators: AdministratorsOperations operations + :vartype administrators: + azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.AdministratorsOperations + :ivar backups: BackupsOperations operations + :vartype backups: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.BackupsOperations + :ivar location_based_capabilities: LocationBasedCapabilitiesOperations operations + :vartype location_based_capabilities: + azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.LocationBasedCapabilitiesOperations + :ivar check_name_availability: CheckNameAvailabilityOperations operations + :vartype check_name_availability: + azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.CheckNameAvailabilityOperations + :ivar check_name_availability_with_location: CheckNameAvailabilityWithLocationOperations + operations + :vartype check_name_availability_with_location: + azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.CheckNameAvailabilityWithLocationOperations + :ivar configurations: ConfigurationsOperations operations + :vartype configurations: + azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.ConfigurationsOperations :ivar databases: DatabasesOperations operations :vartype databases: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.DatabasesOperations - :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations - :vartype get_private_dns_zone_suffix: - azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.GetPrivateDnsZoneSuffixOperations - :ivar servers: ServersOperations operations - :vartype servers: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.ServersOperations - :ivar backups: BackupsOperations operations - :vartype backups: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.BackupsOperations :ivar firewall_rules: FirewallRulesOperations operations :vartype firewall_rules: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.FirewallRulesOperations - :ivar configurations: ConfigurationsOperations operations - :vartype configurations: - azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.ConfigurationsOperations - :ivar check_name_availability: CheckNameAvailabilityOperations operations - :vartype check_name_availability: - azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.CheckNameAvailabilityOperations - :ivar location_based_capabilities: LocationBasedCapabilitiesOperations operations - :vartype location_based_capabilities: - azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.LocationBasedCapabilitiesOperations + :ivar servers: ServersOperations operations + :vartype servers: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.ServersOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.Operations + :ivar get_private_dns_zone_suffix: GetPrivateDnsZoneSuffixOperations operations + :vartype get_private_dns_zone_suffix: + azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.GetPrivateDnsZoneSuffixOperations :ivar virtual_network_subnet_usage: VirtualNetworkSubnetUsageOperations operations :vartype virtual_network_subnet_usage: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.VirtualNetworkSubnetUsageOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.rdbms.postgresql_flexibleservers.aio.operations.Operations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The 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 - :keyword api_version: Api Version. Default value is "2022-01-20-preview". Note that overriding + :keyword api_version: Api Version. Default value is "2022-03-08-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no @@ -74,50 +94,39 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = PostgreSQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = PostgreSQLManagementClientConfiguration( + 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.databases = DatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.servers = ServersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.backups = BackupsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.firewall_rules = FirewallRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.configurations = ConfigurationsOperations( + self.administrators = AdministratorsOperations(self._client, self._config, self._serialize, self._deserialize) + self.backups = BackupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.location_based_capabilities = LocationBasedCapabilitiesOperations( self._client, self._config, self._serialize, self._deserialize ) self.check_name_availability = CheckNameAvailabilityOperations( self._client, self._config, self._serialize, self._deserialize ) - self.location_based_capabilities = LocationBasedCapabilitiesOperations( + self.check_name_availability_with_location = CheckNameAvailabilityWithLocationOperations( self._client, self._config, self._serialize, self._deserialize ) - self.virtual_network_subnet_usage = VirtualNetworkSubnetUsageOperations( + 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.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( self._client, self._config, self._serialize, self._deserialize ) - self.operations = Operations( + self.virtual_network_subnet_usage = VirtualNetworkSubnetUsageOperations( 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 @@ -126,7 +135,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/postgresql_flexibleservers/aio/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/__init__.py index 2cb2a786e327..0e78e3303939 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/__init__.py @@ -6,31 +6,36 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._databases_operations import DatabasesOperations -from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations -from ._servers_operations import ServersOperations +from ._administrators_operations import AdministratorsOperations from ._backups_operations import BackupsOperations -from ._firewall_rules_operations import FirewallRulesOperations -from ._configurations_operations import ConfigurationsOperations -from ._check_name_availability_operations import CheckNameAvailabilityOperations from ._location_based_capabilities_operations import LocationBasedCapabilitiesOperations -from ._virtual_network_subnet_usage_operations import VirtualNetworkSubnetUsageOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._check_name_availability_with_location_operations import CheckNameAvailabilityWithLocationOperations +from ._configurations_operations import ConfigurationsOperations +from ._databases_operations import DatabasesOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._servers_operations import ServersOperations from ._operations import Operations +from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations +from ._virtual_network_subnet_usage_operations import VirtualNetworkSubnetUsageOperations 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__ = [ - 'DatabasesOperations', - 'GetPrivateDnsZoneSuffixOperations', - 'ServersOperations', - 'BackupsOperations', - 'FirewallRulesOperations', - 'ConfigurationsOperations', - 'CheckNameAvailabilityOperations', - 'LocationBasedCapabilitiesOperations', - 'VirtualNetworkSubnetUsageOperations', - 'Operations', + "AdministratorsOperations", + "BackupsOperations", + "LocationBasedCapabilitiesOperations", + "CheckNameAvailabilityOperations", + "CheckNameAvailabilityWithLocationOperations", + "ConfigurationsOperations", + "DatabasesOperations", + "FirewallRulesOperations", + "ServersOperations", + "Operations", + "GetPrivateDnsZoneSuffixOperations", + "VirtualNetworkSubnetUsageOperations", ] __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/postgresql_flexibleservers/aio/operations/_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_administrators_operations.py new file mode 100644 index 000000000000..151f21c15828 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_administrators_operations.py @@ -0,0 +1,596 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._administrators_operations import ( + build_create_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AdministratorsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.rdbms.postgresql_flexibleservers.aio.PostgreSQLManagementClient`'s + :attr:`administrators` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _create_initial( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: Union[_models.ActiveDirectoryAdministratorAdd, IO], + **kwargs: Any + ) -> _models.ActiveDirectoryAdministrator: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ActiveDirectoryAdministrator] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ActiveDirectoryAdministratorAdd") + + request = build_create_request( + resource_group_name=resource_group_name, + server_name=server_name, + object_id=object_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ActiveDirectoryAdministrator", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ActiveDirectoryAdministrator", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @overload + async def begin_create( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: _models.ActiveDirectoryAdministratorAdd, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ActiveDirectoryAdministrator]: + """Creates a new 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :param parameters: The required parameters for adding an active directory administrator for a + server. Required. + :type parameters: + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministratorAdd + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 ActiveDirectoryAdministrator or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ActiveDirectoryAdministrator]: + """Creates a new 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :param parameters: The required parameters for adding an active directory administrator for 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 ActiveDirectoryAdministrator or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: Union[_models.ActiveDirectoryAdministratorAdd, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ActiveDirectoryAdministrator]: + """Creates a new 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :param parameters: The required parameters for adding an active directory administrator for a + server. Is either a model type or a IO type. Required. + :type parameters: + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministratorAdd or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 ActiveDirectoryAdministrator or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ActiveDirectoryAdministrator] + 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, + server_name=server_name, + object_id=object_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ActiveDirectoryAdministrator", 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 + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, server_name: str, object_id: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + server_name=server_name, + object_id=object_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, None, response_headers) + + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, server_name: str, object_id: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes an Active Directory Administrator associated with the 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + 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, + object_id=object_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, 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, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @distributed_trace_async + async def get( + self, resource_group_name: str, server_name: str, object_id: str, **kwargs: Any + ) -> _models.ActiveDirectoryAdministrator: + """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. Required. + :type server_name: str + :param object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ActiveDirectoryAdministrator or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ActiveDirectoryAdministrator] + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + object_id=object_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ActiveDirectoryAdministrator", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @distributed_trace + def list_by_server( + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ActiveDirectoryAdministrator"]: + """List all the AAD administrators 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. 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 ActiveDirectoryAdministrator or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AdministratorListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_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"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AdministratorListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_backups_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_backups_operations.py index 19fa9fac4b3f..061adfa9ed51 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_backups_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_backups_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -21,9 +30,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._backups_operations import build_get_request, build_list_by_server_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class BackupsOperations: """ .. warning:: @@ -43,47 +58,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_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. + """Get specific backup 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -91,65 +106,67 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_flexibleservers.models.ServerBackupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -157,15 +174,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 @@ -182,21 +201,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/backups"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/backups"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_operations.py index 4f1a511165da..92e3612801ed 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_operations.py @@ -6,9 +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, Optional, TypeVar - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._check_name_availability_operations import build_execute_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class CheckNameAvailabilityOperations: """ .. warning:: @@ -41,44 +55,97 @@ 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, + name_availability_request: _models.CheckNameAvailabilityRequest, + *, + 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.postgresql_flexibleservers.models.NameAvailabilityRequest + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default 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.postgresql_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 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.postgresql_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.CheckNameAvailabilityRequest, 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.postgresql_flexibleservers.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, "CheckNameAvailabilityRequest") 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 +153,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_with_location_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_with_location_operations.py new file mode 100644 index 000000000000..894fe1199d74 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_check_name_availability_with_location_operations.py @@ -0,0 +1,189 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._check_name_availability_with_location_operations import build_execute_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CheckNameAvailabilityWithLocationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.rdbms.postgresql_flexibleservers.aio.PostgreSQLManagementClient`'s + :attr:`check_name_availability_with_location` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def execute( + self, + location_name: str, + name_availability_request: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param location_name: The name of the location. Required. + :type location_name: str + :param name_availability_request: The required parameters for checking if resource name is + available. Required. + :type name_availability_request: + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default 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.postgresql_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 resource. + + :param location_name: The name of the location. Required. + :type location_name: str + :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.postgresql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def execute( + self, + location_name: str, + name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], + **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param location_name: The name of the location. Required. + :type location_name: str + :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.postgresql_flexibleservers.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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.postgresql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] + + 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, "CheckNameAvailabilityRequest") + + request = build_execute_request( + location_name=location_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.execute.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NameAvailability", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_configurations_operations.py index d7b10a7325ac..a9f588bb8fe2 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_configurations_operations.py @@ -6,10 +6,19 @@ # 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 +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +31,21 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._configurations_operations import build_get_request, build_list_by_server_request, build_put_request_initial, build_update_request_initial -T = TypeVar('T') +from ...operations._configurations_operations import ( + build_get_request, + build_list_by_server_request, + build_put_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ConfigurationsOperations: """ .. warning:: @@ -45,46 +65,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 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 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.postgresql_flexibleservers.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -92,15 +114,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 @@ -117,65 +141,63 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations"} # 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -183,57 +205,68 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore async def _update_initial( self, resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.ConfigurationForUpdate, 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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Configuration') - - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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, "ConfigurationForUpdate") + + 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, ) @@ -241,27 +274,113 @@ 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]: + if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + @overload + async def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: _models.ConfigurationForUpdate, + *, + 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: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationForUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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.postgresql_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.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_update( @@ -269,19 +388,25 @@ async def begin_update( resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.ConfigurationForUpdate, 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. + :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. - :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :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.postgresql_flexibleservers.models.ConfigurationForUpdate or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -294,20 +419,19 @@ async def begin_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -316,71 +440,82 @@ 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, 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_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore async def _put_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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Configuration') - - request = build_put_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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_put_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._put_initial.metadata['url'], + content=_content, + template_url=self._put_initial.metadata["url"], headers=_headers, params=_params, ) @@ -388,47 +523,59 @@ async def _put_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]: + if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _put_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - + _put_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - @distributed_trace_async + @overload async def begin_put( 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.postgresql_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 @@ -441,20 +588,98 @@ async def begin_put( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_put( + 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.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_put( + 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.postgresql_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 + this 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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._put_initial( # type: ignore resource_group_name=resource_group_name, @@ -463,36 +688,34 @@ async def begin_put( 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, 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_put.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_put.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_databases_operations.py index 023bdb4b6f4f..c04bbe954af4 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_databases_operations.py @@ -6,10 +6,19 @@ # 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 +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +31,21 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._databases_operations import build_create_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request -T = TypeVar('T') +from ...operations._databases_operations import ( + build_create_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class DatabasesOperations: """ .. warning:: @@ -45,38 +65,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") - async def _create_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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Database') - - request = build_create_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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_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_initial.metadata['url'], + content=_content, + template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) @@ -84,50 +115,138 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} 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 response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - - @distributed_trace_async + @overload async def begin_create( 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.postgresql_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.postgresql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + 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.postgresql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + 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.postgresql_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 @@ -140,20 +259,19 @@ async def begin_create( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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_initial( # type: ignore resource_group_name=resource_group_name, @@ -162,66 +280,65 @@ 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('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, 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_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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,37 +346,37 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 +388,95 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +484,67 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_flexibleservers.models.DatabaseListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +552,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,21 +579,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_firewall_rules_operations.py index ecd4928f6ce5..1d6188688617 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_firewall_rules_operations.py @@ -6,10 +6,19 @@ # 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 +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +31,21 @@ 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, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class FirewallRulesOperations: """ .. warning:: @@ -45,38 +65,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") - 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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'FirewallRule') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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( 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,50 +115,59 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} 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 response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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 @@ -140,20 +180,98 @@ async def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FirewallRule] - :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, + 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.postgresql_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.postgresql_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 + this 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +280,65 @@ 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, 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_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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,37 +346,37 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -271,97 +388,95 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: """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 - :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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +484,67 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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.postgresql_flexibleservers.models.FirewallRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +552,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,21 +579,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py index de61762fb0a6..fdbe477ed672 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class GetPrivateDnsZoneSuffixOperations: """ .. warning:: @@ -41,34 +55,34 @@ 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 - ) -> str: + async def execute(self, **kwargs: Any) -> str: """Get private DNS zone suffix in the cloud. :keyword callable cls: A custom type or function that will be passed the direct response - :return: str, or the result of cls(response) + :return: str or the result of cls(response) :rtype: str - :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', "2022-01-20-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[str] - 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 +90,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('str', pipeline_response) + deserialized = self._deserialize("str", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/providers/Microsoft.DBforPostgreSQL/getPrivateDnsZoneSuffix"} # type: ignore - + execute.metadata = {"url": "/providers/Microsoft.DBforPostgreSQL/getPrivateDnsZoneSuffix"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_location_based_capabilities_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_location_based_capabilities_operations.py index 185c6210b780..b4f74690c4f9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_location_based_capabilities_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_location_based_capabilities_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +29,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._location_based_capabilities_operations import build_execute_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LocationBasedCapabilitiesOperations: """ .. warning:: @@ -42,42 +57,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 execute( - self, - location_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.CapabilitiesListResult]: + def execute(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.postgresql_flexibleservers.models.CapabilitiesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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_execute_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.execute.metadata['url'], + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -85,14 +101,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_execute_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,21 +128,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/capabilities"} # type: ignore + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/capabilities"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_operations.py index 437558d8acd5..bdc0e9b7d83a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class Operations: """ .. warning:: @@ -41,34 +55,34 @@ 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 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.postgresql_flexibleservers.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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -76,22 +90,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/operations"} # type: ignore - + list.metadata = {"url": "/providers/Microsoft.DBforPostgreSQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_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/postgresql_flexibleservers/aio/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_servers_operations.py index 2318a958e102..0a0729140b79 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_servers_operations.py @@ -6,10 +6,19 @@ # 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 +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +31,26 @@ 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 -T = TypeVar('T') +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, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServersOperations: """ .. warning:: @@ -45,36 +70,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") - 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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Server') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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,47 +114,121 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('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.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. :param resource_group_name: The 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.postgresql_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.postgresql_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. + + :param resource_group_name: The 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.postgresql_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. + + :param resource_group_name: The 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.postgresql_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 @@ -135,20 +241,19 @@ async def begin_create( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -156,69 +261,76 @@ 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, 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_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'ServerForUpdate') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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, "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, ) @@ -226,45 +338,92 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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.postgresql_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 @@ -277,20 +436,52 @@ async def begin_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.postgresql_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.postgresql_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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -298,64 +489,64 @@ 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, 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_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -363,34 +554,33 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -402,92 +592,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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -495,60 +682,62 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -556,14 +745,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 @@ -580,55 +772,55 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -636,13 +828,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 @@ -659,57 +855,66 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/flexibleServers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/flexibleServers"} # type: ignore async def _restart_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - parameters: Optional[_models.RestartParameter] = None, + parameters: Optional[Union[_models.RestartParameter, IO]] = None, **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', "2022-01-20-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] - - if parameters is not None: - _json = self._serialize.body(parameters, 'RestartParameter') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters else: - _json = None + if parameters is not None: + _json = self._serialize.body(parameters, "RestartParameter") + else: + _json = 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, 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, ) @@ -717,38 +922,116 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _restart_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Optional[_models.RestartParameter] = None, + *, + 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 parameters for restarting a server. Default value is None. :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.RestartParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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: Optional[IO] = None, + *, + 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 parameters for restarting a server. Default value is None. + :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: Optional[Union[_models.RestartParameter, IO]] = None, + **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 parameters for restarting a server. Is either a model type or a IO type. + Default value is None. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.RestartParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -759,20 +1042,19 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -780,62 +1062,61 @@ 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, 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_restart.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -843,34 +1124,33 @@ 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _start_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -882,80 +1162,78 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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_start.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start"} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -963,34 +1241,33 @@ 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _stop_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -1002,52 +1279,49 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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_stop.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop"} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_virtual_network_subnet_usage_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_virtual_network_subnet_usage_operations.py index 57bb99109e26..b0be8523c862 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_virtual_network_subnet_usage_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/aio/operations/_virtual_network_subnet_usage_operations.py @@ -6,9 +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, Optional, TypeVar - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._virtual_network_subnet_usage_operations import build_execute_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class VirtualNetworkSubnetUsageOperations: """ .. warning:: @@ -41,47 +55,103 @@ 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.postgresql_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.postgresql_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.postgresql_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.postgresql_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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +159,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/__init__.py index 3ccde958fd5a..a25b8177f4ac 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/__init__.py @@ -6,16 +6,26 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from ._models_py3 import ActiveDirectoryAdministrator +from ._models_py3 import ActiveDirectoryAdministratorAdd +from ._models_py3 import AdministratorListResult +from ._models_py3 import AuthConfig from ._models_py3 import Backup from ._models_py3 import CapabilitiesListResult from ._models_py3 import CapabilityProperties +from ._models_py3 import CheckNameAvailabilityRequest +from ._models_py3 import CheckNameAvailabilityResponse from ._models_py3 import Configuration +from ._models_py3 import ConfigurationForUpdate from ._models_py3 import ConfigurationListResult +from ._models_py3 import DataEncryption from ._models_py3 import Database from ._models_py3 import DatabaseListResult from ._models_py3 import DelegatedSubnetUsage from ._models_py3 import ErrorAdditionalInfo +from ._models_py3 import ErrorDetail from ._models_py3 import ErrorResponse +from ._models_py3 import FastProvisioningEditionCapability from ._models_py3 import FirewallRule from ._models_py3 import FirewallRuleListResult from ._models_py3 import FlexibleServerEditionCapability @@ -23,7 +33,6 @@ from ._models_py3 import HyperscaleNodeEditionCapability from ._models_py3 import MaintenanceWindow from ._models_py3 import NameAvailability -from ._models_py3 import NameAvailabilityRequest from ._models_py3 import Network from ._models_py3 import NodeTypeCapability from ._models_py3 import Operation @@ -42,88 +51,111 @@ from ._models_py3 import Storage from ._models_py3 import StorageEditionCapability from ._models_py3 import StorageMBCapability +from ._models_py3 import StorageTierCapability from ._models_py3 import SystemData from ._models_py3 import TrackedResource +from ._models_py3 import UserAssignedIdentity +from ._models_py3 import UserIdentity from ._models_py3 import VcoreCapability from ._models_py3 import VirtualNetworkSubnetUsageParameter from ._models_py3 import VirtualNetworkSubnetUsageResult - -from ._postgre_sql_management_client_enums import ( - ConfigurationDataType, - CreateMode, - CreateModeForUpdate, - CreatedByType, - FailoverMode, - GeoRedundantBackupEnum, - HighAvailabilityMode, - OperationOrigin, - Reason, - ServerHAState, - ServerPublicNetworkAccessState, - ServerState, - ServerVersion, - SkuTier, -) +from ._postgre_sql_management_client_enums import ArmServerKeyType +from ._postgre_sql_management_client_enums import CheckNameAvailabilityReason +from ._postgre_sql_management_client_enums import ConfigurationDataType +from ._postgre_sql_management_client_enums import CreateMode +from ._postgre_sql_management_client_enums import CreateModeForUpdate +from ._postgre_sql_management_client_enums import CreatedByType +from ._postgre_sql_management_client_enums import FailoverMode +from ._postgre_sql_management_client_enums import GeoRedundantBackupEnum +from ._postgre_sql_management_client_enums import HighAvailabilityMode +from ._postgre_sql_management_client_enums import IdentityType +from ._postgre_sql_management_client_enums import OperationOrigin +from ._postgre_sql_management_client_enums import Origin +from ._postgre_sql_management_client_enums import PrincipalType +from ._postgre_sql_management_client_enums import ReplicationRole +from ._postgre_sql_management_client_enums import ServerHAState +from ._postgre_sql_management_client_enums import ServerPublicNetworkAccessState +from ._postgre_sql_management_client_enums import ServerState +from ._postgre_sql_management_client_enums import ServerVersion +from ._postgre_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__ = [ - 'Backup', - 'CapabilitiesListResult', - 'CapabilityProperties', - 'Configuration', - 'ConfigurationListResult', - 'Database', - 'DatabaseListResult', - 'DelegatedSubnetUsage', - 'ErrorAdditionalInfo', - 'ErrorResponse', - 'FirewallRule', - 'FirewallRuleListResult', - 'FlexibleServerEditionCapability', - 'HighAvailability', - 'HyperscaleNodeEditionCapability', - 'MaintenanceWindow', - 'NameAvailability', - 'NameAvailabilityRequest', - 'Network', - 'NodeTypeCapability', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'ProxyResource', - 'Resource', - 'RestartParameter', - 'Server', - 'ServerBackup', - 'ServerBackupListResult', - 'ServerForUpdate', - 'ServerListResult', - 'ServerVersionCapability', - 'Sku', - 'Storage', - 'StorageEditionCapability', - 'StorageMBCapability', - 'SystemData', - 'TrackedResource', - 'VcoreCapability', - 'VirtualNetworkSubnetUsageParameter', - 'VirtualNetworkSubnetUsageResult', - 'ConfigurationDataType', - 'CreateMode', - 'CreateModeForUpdate', - 'CreatedByType', - 'FailoverMode', - 'GeoRedundantBackupEnum', - 'HighAvailabilityMode', - 'OperationOrigin', - 'Reason', - 'ServerHAState', - 'ServerPublicNetworkAccessState', - 'ServerState', - 'ServerVersion', - 'SkuTier', + "ActiveDirectoryAdministrator", + "ActiveDirectoryAdministratorAdd", + "AdministratorListResult", + "AuthConfig", + "Backup", + "CapabilitiesListResult", + "CapabilityProperties", + "CheckNameAvailabilityRequest", + "CheckNameAvailabilityResponse", + "Configuration", + "ConfigurationForUpdate", + "ConfigurationListResult", + "DataEncryption", + "Database", + "DatabaseListResult", + "DelegatedSubnetUsage", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "FastProvisioningEditionCapability", + "FirewallRule", + "FirewallRuleListResult", + "FlexibleServerEditionCapability", + "HighAvailability", + "HyperscaleNodeEditionCapability", + "MaintenanceWindow", + "NameAvailability", + "Network", + "NodeTypeCapability", + "Operation", + "OperationDisplay", + "OperationListResult", + "ProxyResource", + "Resource", + "RestartParameter", + "Server", + "ServerBackup", + "ServerBackupListResult", + "ServerForUpdate", + "ServerListResult", + "ServerVersionCapability", + "Sku", + "Storage", + "StorageEditionCapability", + "StorageMBCapability", + "StorageTierCapability", + "SystemData", + "TrackedResource", + "UserAssignedIdentity", + "UserIdentity", + "VcoreCapability", + "VirtualNetworkSubnetUsageParameter", + "VirtualNetworkSubnetUsageResult", + "ArmServerKeyType", + "CheckNameAvailabilityReason", + "ConfigurationDataType", + "CreateMode", + "CreateModeForUpdate", + "CreatedByType", + "FailoverMode", + "GeoRedundantBackupEnum", + "HighAvailabilityMode", + "IdentityType", + "OperationOrigin", + "Origin", + "PrincipalType", + "ReplicationRole", + "ServerHAState", + "ServerPublicNetworkAccessState", + "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/postgresql_flexibleservers/models/_models_py3.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models_py3.py index 4555a656d086..f92b96d6f19d 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_models_py3.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_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. @@ -9,14 +10,283 @@ import datetime from typing import 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 -class Backup(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. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.system_data = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + + +class ActiveDirectoryAdministrator(ProxyResource): + """Represents an Active Directory administrator. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :ivar principal_type: The principal type used to represent the type of Active Directory + Administrator. Known values are: "Unknown", "User", "Group", and "ServicePrincipal". + :vartype principal_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.PrincipalType + :ivar principal_name: Active Directory administrator principal name. + :vartype principal_name: str + :ivar object_id: The objectId of the Active Directory administrator. + :vartype object_id: str + :ivar tenant_id: The tenantId of the Active Directory administrator. + :vartype tenant_id: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "principal_type": {"key": "properties.principalType", "type": "str"}, + "principal_name": {"key": "properties.principalName", "type": "str"}, + "object_id": {"key": "properties.objectId", "type": "str"}, + "tenant_id": {"key": "properties.tenantId", "type": "str"}, + } + + def __init__( + self, + *, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, + principal_name: Optional[str] = None, + object_id: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_type: The principal type used to represent the type of Active Directory + Administrator. Known values are: "Unknown", "User", "Group", and "ServicePrincipal". + :paramtype principal_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.PrincipalType + :keyword principal_name: Active Directory administrator principal name. + :paramtype principal_name: str + :keyword object_id: The objectId of the Active Directory administrator. + :paramtype object_id: str + :keyword tenant_id: The tenantId of the Active Directory administrator. + :paramtype tenant_id: str + """ + super().__init__(**kwargs) + self.principal_type = principal_type + self.principal_name = principal_name + self.object_id = object_id + self.tenant_id = tenant_id + + +class ActiveDirectoryAdministratorAdd(_serialization.Model): + """Represents an Active Directory administrator. + + :ivar principal_type: The principal type used to represent the type of Active Directory + Administrator. Known values are: "Unknown", "User", "Group", and "ServicePrincipal". + :vartype principal_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.PrincipalType + :ivar principal_name: Active Directory administrator principal name. + :vartype principal_name: str + :ivar tenant_id: The tenantId of the Active Directory administrator. + :vartype tenant_id: str + """ + + _attribute_map = { + "principal_type": {"key": "properties.principalType", "type": "str"}, + "principal_name": {"key": "properties.principalName", "type": "str"}, + "tenant_id": {"key": "properties.tenantId", "type": "str"}, + } + + def __init__( + self, + *, + principal_type: Optional[Union[str, "_models.PrincipalType"]] = None, + principal_name: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs + ): + """ + :keyword principal_type: The principal type used to represent the type of Active Directory + Administrator. Known values are: "Unknown", "User", "Group", and "ServicePrincipal". + :paramtype principal_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.PrincipalType + :keyword principal_name: Active Directory administrator principal name. + :paramtype principal_name: str + :keyword tenant_id: The tenantId of the Active Directory administrator. + :paramtype tenant_id: str + """ + super().__init__(**kwargs) + self.principal_type = principal_type + self.principal_name = principal_name + self.tenant_id = tenant_id + + +class AdministratorListResult(_serialization.Model): + """A list of active directory administrators. + + :ivar value: The list of active directory administrators. + :vartype value: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :ivar next_link: The link used to get the next page of active directory. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ActiveDirectoryAdministrator]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.ActiveDirectoryAdministrator"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + """ + :keyword value: The list of active directory administrators. + :paramtype value: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :keyword next_link: The link used to get the next page of active directory. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AuthConfig(_serialization.Model): + """Authentication configuration properties of a server. + + :ivar active_directory_auth_enabled: If true, Azure Active Directory authentication is enabled. + :vartype active_directory_auth_enabled: bool + :ivar password_auth_enabled: If true, Password authentication is enabled. + :vartype password_auth_enabled: bool + :ivar tenant_id: Tenant id of the server. + :vartype tenant_id: str + """ + + _attribute_map = { + "active_directory_auth_enabled": {"key": "activeDirectoryAuthEnabled", "type": "bool"}, + "password_auth_enabled": {"key": "passwordAuthEnabled", "type": "bool"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + } + + def __init__( + self, + *, + active_directory_auth_enabled: Optional[bool] = None, + password_auth_enabled: bool = True, + tenant_id: str = "", + **kwargs + ): + """ + :keyword active_directory_auth_enabled: If true, Azure Active Directory authentication is + enabled. + :paramtype active_directory_auth_enabled: bool + :keyword password_auth_enabled: If true, Password authentication is enabled. + :paramtype password_auth_enabled: bool + :keyword tenant_id: Tenant id of the server. + :paramtype tenant_id: str + """ + super().__init__(**kwargs) + self.active_directory_auth_enabled = active_directory_auth_enabled + self.password_auth_enabled = password_auth_enabled + self.tenant_id = tenant_id + + +class Backup(_serialization.Model): """Backup properties of a server. Variables are only populated by the server, and will be ignored when sending a request. @@ -24,7 +294,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: A value indicating whether Geo-Redundant backup is enabled on the - server. Known values are: "Enabled", "Disabled". Default value: "Disabled". + server. Known values are: "Enabled" and "Disabled". :vartype geo_redundant_backup: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.GeoRedundantBackupEnum :ivar earliest_restore_date: The earliest restore point time (ISO8601 format) for server. @@ -32,37 +302,37 @@ 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__( self, *, - backup_retention_days: Optional[int] = 7, - geo_redundant_backup: Optional[Union[str, "_models.GeoRedundantBackupEnum"]] = "Disabled", + backup_retention_days: int = 7, + geo_redundant_backup: Union[str, "_models.GeoRedundantBackupEnum"] = "Disabled", **kwargs ): """ :keyword backup_retention_days: Backup retention days for the server. :paramtype backup_retention_days: int :keyword geo_redundant_backup: A value indicating whether Geo-Redundant backup is enabled on - the server. Known values are: "Enabled", "Disabled". Default value: "Disabled". + the server. Known values are: "Enabled" and "Disabled". :paramtype geo_redundant_backup: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.GeoRedundantBackupEnum """ - 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. @@ -74,27 +344,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. @@ -118,39 +384,54 @@ class CapabilityProperties(msrest.serialization.Model): :ivar supported_hyperscale_node_editions: :vartype supported_hyperscale_node_editions: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.HyperscaleNodeEditionCapability] + :ivar fast_provisioning_supported: A value indicating whether fast provisioning is supported in + this region. + :vartype fast_provisioning_supported: bool + :ivar supported_fast_provisioning_editions: + :vartype supported_fast_provisioning_editions: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.FastProvisioningEditionCapability] :ivar status: The status. :vartype status: str """ _validation = { - 'zone': {'readonly': True}, - 'supported_ha_mode': {'readonly': True}, - 'geo_backup_supported': {'readonly': True}, - 'zone_redundant_ha_supported': {'readonly': True}, - 'zone_redundant_ha_and_geo_backup_supported': {'readonly': True}, - 'supported_flexible_server_editions': {'readonly': True}, - 'supported_hyperscale_node_editions': {'readonly': True}, - 'status': {'readonly': True}, + "zone": {"readonly": True}, + "supported_ha_mode": {"readonly": True}, + "geo_backup_supported": {"readonly": True}, + "zone_redundant_ha_supported": {"readonly": True}, + "zone_redundant_ha_and_geo_backup_supported": {"readonly": True}, + "supported_flexible_server_editions": {"readonly": True}, + "supported_hyperscale_node_editions": {"readonly": True}, + "fast_provisioning_supported": {"readonly": True}, + "supported_fast_provisioning_editions": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'zone': {'key': 'zone', 'type': 'str'}, - 'supported_ha_mode': {'key': 'supportedHAMode', 'type': '[str]'}, - 'geo_backup_supported': {'key': 'geoBackupSupported', 'type': 'bool'}, - 'zone_redundant_ha_supported': {'key': 'zoneRedundantHaSupported', 'type': 'bool'}, - 'zone_redundant_ha_and_geo_backup_supported': {'key': 'zoneRedundantHaAndGeoBackupSupported', 'type': 'bool'}, - 'supported_flexible_server_editions': {'key': 'supportedFlexibleServerEditions', 'type': '[FlexibleServerEditionCapability]'}, - 'supported_hyperscale_node_editions': {'key': 'supportedHyperscaleNodeEditions', 'type': '[HyperscaleNodeEditionCapability]'}, - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(CapabilityProperties, self).__init__(**kwargs) + "zone": {"key": "zone", "type": "str"}, + "supported_ha_mode": {"key": "supportedHAMode", "type": "[str]"}, + "geo_backup_supported": {"key": "geoBackupSupported", "type": "bool"}, + "zone_redundant_ha_supported": {"key": "zoneRedundantHaSupported", "type": "bool"}, + "zone_redundant_ha_and_geo_backup_supported": {"key": "zoneRedundantHaAndGeoBackupSupported", "type": "bool"}, + "supported_flexible_server_editions": { + "key": "supportedFlexibleServerEditions", + "type": "[FlexibleServerEditionCapability]", + }, + "supported_hyperscale_node_editions": { + "key": "supportedHyperscaleNodeEditions", + "type": "[HyperscaleNodeEditionCapability]", + }, + "fast_provisioning_supported": {"key": "fastProvisioningSupported", "type": "bool"}, + "supported_fast_provisioning_editions": { + "key": "supportedFastProvisioningEditions", + "type": "[FastProvisioningEditionCapability]", + }, + "status": {"key": "status", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.zone = None self.supported_ha_mode = None self.geo_backup_supported = None @@ -158,50 +439,82 @@ def __init__( self.zone_redundant_ha_and_geo_backup_supported = None self.supported_flexible_server_editions = None self.supported_hyperscale_node_editions = None + self.fast_provisioning_supported = None + self.supported_fast_provisioning_editions = None self.status = None -class Resource(msrest.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. +class CheckNameAvailabilityRequest(_serialization.Model): + """The check availability request body. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. + :ivar name: The name of the resource for which availability needs to be checked. :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". + :ivar type: The resource type. :vartype type: str """ - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword name: The name of the resource for which availability needs to be checked. + :paramtype name: str + :keyword type: The resource type. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class CheckNameAvailabilityResponse(_serialization.Model): + """The check availability result. + + :ivar name_available: Indicates if the resource name is available. + :vartype name_available: bool + :ivar reason: The reason why the given name is not available. Known values are: "Invalid" and + "AlreadyExists". + :vartype reason: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityReason + :ivar message: Detailed reason why the given name is available. + :vartype message: str + """ + _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, } def __init__( self, + *, + name_available: Optional[bool] = None, + reason: Optional[Union[str, "_models.CheckNameAvailabilityReason"]] = None, + message: Optional[str] = None, **kwargs ): """ + :keyword name_available: Indicates if the resource name is available. + :paramtype name_available: bool + :keyword reason: The reason why the given name is not available. Known values are: "Invalid" + and "AlreadyExists". + :paramtype reason: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityReason + :keyword message: Detailed reason why the given name is available. + :paramtype message: str """ - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None + super().__init__(**kwargs) + self.name_available = name_available + self.reason = reason + self.message = message -class ProxyResource(Resource): - """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. +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. @@ -213,44 +526,95 @@ class ProxyResource(Resource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :ivar value: Value of the configuration. + :vartype value: str + :ivar description: Description of the configuration. + :vartype description: str + :ivar default_value: Default value of the configuration. + :vartype default_value: str + :ivar data_type: Data type of the configuration. Known values are: "Boolean", "Numeric", + "Integer", and "Enumeration". + :vartype data_type: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationDataType + :ivar allowed_values: Allowed values of the configuration. + :vartype allowed_values: str + :ivar source: Source of the configuration. + :vartype source: str + :ivar is_dynamic_config: Configuration dynamic or static. + :vartype is_dynamic_config: bool + :ivar is_read_only: Configuration read-only or not. + :vartype is_read_only: bool + :ivar is_config_pending_restart: Configuration is pending restart or not. + :vartype is_config_pending_restart: bool + :ivar unit: Configuration unit. + :vartype unit: str + :ivar documentation_link: Configuration documentation link. + :vartype documentation_link: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'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_dynamic_config": {"readonly": True}, + "is_read_only": {"readonly": True}, + "is_config_pending_restart": {"readonly": True}, + "unit": {"readonly": True}, + "documentation_link": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): + "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_dynamic_config": {"key": "properties.isDynamicConfig", "type": "bool"}, + "is_read_only": {"key": "properties.isReadOnly", "type": "bool"}, + "is_config_pending_restart": {"key": "properties.isConfigPendingRestart", "type": "bool"}, + "unit": {"key": "properties.unit", "type": "str"}, + "documentation_link": {"key": "properties.documentationLink", "type": "str"}, + } + + 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(ProxyResource, self).__init__(**kwargs) + super().__init__(**kwargs) + self.value = value + self.description = None + self.default_value = None + self.data_type = None + self.allowed_values = None + self.source = source + self.is_dynamic_config = None + self.is_read_only = None + self.is_config_pending_restart = None + self.unit = None + self.documentation_link = None -class Configuration(ProxyResource): +class ConfigurationForUpdate(_serialization.Model): # pylint: disable=too-many-instance-attributes """Represents a Configuration. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: The system metadata relating to this resource. - :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData :ivar value: Value of the configuration. :vartype value: str :ivar description: Description of the configuration. @@ -258,7 +622,7 @@ class Configuration(ProxyResource): :ivar default_value: Default value of the configuration. :vartype default_value: str :ivar data_type: Data type of the configuration. Known values are: "Boolean", "Numeric", - "Integer", "Enumeration". + "Integer", and "Enumeration". :vartype data_type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationDataType :ivar allowed_values: Allowed values of the configuration. @@ -278,54 +642,39 @@ class Configuration(ProxyResource): """ _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_dynamic_config': {'readonly': True}, - 'is_read_only': {'readonly': True}, - 'is_config_pending_restart': {'readonly': True}, - 'unit': {'readonly': True}, - 'documentation_link': {'readonly': True}, + "description": {"readonly": True}, + "default_value": {"readonly": True}, + "data_type": {"readonly": True}, + "allowed_values": {"readonly": True}, + "is_dynamic_config": {"readonly": True}, + "is_read_only": {"readonly": True}, + "is_config_pending_restart": {"readonly": True}, + "unit": {"readonly": True}, + "documentation_link": {"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_dynamic_config': {'key': 'properties.isDynamicConfig', 'type': 'bool'}, - 'is_read_only': {'key': 'properties.isReadOnly', 'type': 'bool'}, - 'is_config_pending_restart': {'key': 'properties.isConfigPendingRestart', 'type': 'bool'}, - 'unit': {'key': 'properties.unit', 'type': 'str'}, - 'documentation_link': {'key': 'properties.documentationLink', '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"}, + "is_dynamic_config": {"key": "properties.isDynamicConfig", "type": "bool"}, + "is_read_only": {"key": "properties.isReadOnly", "type": "bool"}, + "is_config_pending_restart": {"key": "properties.isConfigPendingRestart", "type": "bool"}, + "unit": {"key": "properties.unit", "type": "str"}, + "documentation_link": {"key": "properties.documentationLink", "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) - self.system_data = None + super().__init__(**kwargs) self.value = value self.description = None self.default_value = None @@ -339,7 +688,7 @@ def __init__( self.documentation_link = None -class ConfigurationListResult(msrest.serialization.Model): +class ConfigurationListResult(_serialization.Model): """A list of server configurations. :ivar value: The list of server configurations. @@ -349,16 +698,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. @@ -366,7 +711,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 @@ -384,7 +729,8 @@ class Database(ProxyResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar system_data: The system metadata relating to this resource. + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData :ivar charset: The charset of the database. :vartype charset: str @@ -393,41 +739,36 @@ 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}, + "charset": {"pattern": r"^[a-zA-Z]+\w*$"}, + "collation": {"pattern": r"^[a-zA-Z\-]+([. ]|\w)*$"}, } _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) - self.system_data = None + 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. @@ -437,61 +778,94 @@ 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.postgresql_flexibleservers.models.Database] :keyword next_link: The link used to get the next page of databases. :paramtype next_link: str """ - super(DatabaseListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class DelegatedSubnetUsage(msrest.serialization.Model): +class DataEncryption(_serialization.Model): + """Data encryption properties of a server. + + :ivar primary_key_uri: URI for the key for data encryption for primary server. + :vartype primary_key_uri: str + :ivar primary_user_assigned_identity_id: Resource Id for the User assigned identity to be used + for data encryption for primary server. + :vartype primary_user_assigned_identity_id: str + :ivar type: Data encryption type to depict if it is System assigned vs Azure Key vault. Known + values are: "SystemAssigned" and "AzureKeyVault". + :vartype type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ArmServerKeyType + """ + + _attribute_map = { + "primary_key_uri": {"key": "primaryKeyURI", "type": "str"}, + "primary_user_assigned_identity_id": {"key": "primaryUserAssignedIdentityId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + primary_key_uri: Optional[str] = None, + primary_user_assigned_identity_id: Optional[str] = None, + type: Optional[Union[str, "_models.ArmServerKeyType"]] = None, + **kwargs + ): + """ + :keyword primary_key_uri: URI for the key for data encryption for primary server. + :paramtype primary_key_uri: str + :keyword primary_user_assigned_identity_id: Resource Id for the User assigned identity to be + used for data encryption for primary server. + :paramtype primary_user_assigned_identity_id: str + :keyword type: Data encryption type to depict if it is System assigned vs Azure Key vault. + Known values are: "SystemAssigned" and "AzureKeyVault". + :paramtype type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ArmServerKeyType + """ + super().__init__(**kwargs) + self.primary_key_uri = primary_key_uri + self.primary_user_assigned_identity_id = primary_user_assigned_identity_id + self.type = type + + +class DelegatedSubnetUsage(_serialization.Model): """Delegated subnet usage data. Variables are only populated by the server, and will be ignored when sending a request. - :ivar subnet_name: name of the subnet. + :ivar subnet_name: Name of the delegated subnet for which IP addresses are in use. :vartype subnet_name: str - :ivar usage: Number of used delegated subnets. - :vartype usage: long + :ivar usage: Number of IP addresses used by the delegated subnet. + :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. @@ -499,32 +873,28 @@ 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): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). +class ErrorDetail(_serialization.Model): + """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -535,35 +905,31 @@ class ErrorResponse(msrest.serialization.Model): :ivar target: The error target. :vartype target: str :ivar details: The error details. - :vartype details: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorResponse] + :vartype details: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorDetail] :ivar additional_info: The error additional info. :vartype additional_info: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorAdditionalInfo] """ _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": "[ErrorDetail]"}, + "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 @@ -571,6 +937,59 @@ def __init__( self.additional_info = None +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class FastProvisioningEditionCapability(_serialization.Model): + """FastProvisioningEditionCapability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar supported_sku: Fast provisioning supported sku name. + :vartype supported_sku: str + :ivar supported_storage_gb: Fast provisioning supported storage in Gb. + :vartype supported_storage_gb: int + :ivar supported_server_versions: Fast provisioning supported version. + :vartype supported_server_versions: str + """ + + _validation = { + "supported_sku": {"readonly": True}, + "supported_storage_gb": {"readonly": True}, + "supported_server_versions": {"readonly": True}, + } + + _attribute_map = { + "supported_sku": {"key": "supportedSku", "type": "str"}, + "supported_storage_gb": {"key": "supportedStorageGb", "type": "int"}, + "supported_server_versions": {"key": "supportedServerVersions", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.supported_sku = None + self.supported_storage_gb = None + self.supported_server_versions = None + + class FirewallRule(ProxyResource): """Represents a server firewall rule. @@ -586,56 +1005,56 @@ class FirewallRule(ProxyResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar system_data: The system metadata relating to this resource. + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. :vartype system_data: ~azure.mgmt.rdbms.postgresql_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) - self.system_data = None + 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. @@ -645,16 +1064,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. @@ -662,12 +1077,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 FlexibleServerEditionCapability(msrest.serialization.Model): +class FlexibleServerEditionCapability(_serialization.Model): """Flexible server edition capabilities. Variables are only populated by the server, and will be ignored when sending a request. @@ -685,79 +1100,75 @@ class FlexibleServerEditionCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'supported_storage_editions': {'readonly': True}, - 'supported_server_versions': {'readonly': True}, - 'status': {'readonly': True}, + "name": {"readonly": True}, + "supported_storage_editions": {"readonly": True}, + "supported_server_versions": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, - 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "supported_storage_editions": {"key": "supportedStorageEditions", "type": "[StorageEditionCapability]"}, + "supported_server_versions": {"key": "supportedServerVersions", "type": "[ServerVersionCapability]"}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(FlexibleServerEditionCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.supported_storage_editions = None self.supported_server_versions = None self.status = None -class HighAvailability(msrest.serialization.Model): +class HighAvailability(_serialization.Model): """High availability properties of a server. Variables are only populated by the server, and will be ignored when sending a request. - :ivar mode: The HA mode for the server. Known values are: "Disabled", "ZoneRedundant", - "SameZone". Default value: "Disabled". + :ivar mode: The HA mode for the server. Known values are: "Disabled", "ZoneRedundant", and + "SameZone". :vartype mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailabilityMode :ivar state: A state of a HA server that is visible to user. Known values are: "NotEnabled", - "CreatingStandby", "ReplicatingData", "FailingOver", "Healthy", "RemovingStandby". + "CreatingStandby", "ReplicatingData", "FailingOver", "Healthy", and "RemovingStandby". :vartype state: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerHAState :ivar standby_availability_zone: availability zone information of the standby. :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__( self, *, - mode: Optional[Union[str, "_models.HighAvailabilityMode"]] = "Disabled", - standby_availability_zone: Optional[str] = "", + mode: Union[str, "_models.HighAvailabilityMode"] = "Disabled", + standby_availability_zone: str = "", **kwargs ): """ - :keyword mode: The HA mode for the server. Known values are: "Disabled", "ZoneRedundant", - "SameZone". Default value: "Disabled". + :keyword mode: The HA mode for the server. Known values are: "Disabled", "ZoneRedundant", and + "SameZone". :paramtype mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.HighAvailabilityMode :keyword standby_availability_zone: availability zone information of the standby. :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 HyperscaleNodeEditionCapability(msrest.serialization.Model): +class HyperscaleNodeEditionCapability(_serialization.Model): """Hyperscale node edition capabilities. Variables are only populated by the server, and will be ignored when sending a request. @@ -778,28 +1189,24 @@ class HyperscaleNodeEditionCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'supported_storage_editions': {'readonly': True}, - 'supported_server_versions': {'readonly': True}, - 'supported_node_types': {'readonly': True}, - 'status': {'readonly': True}, + "name": {"readonly": True}, + "supported_storage_editions": {"readonly": True}, + "supported_server_versions": {"readonly": True}, + "supported_node_types": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, - 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, - 'supported_node_types': {'key': 'supportedNodeTypes', 'type': '[NodeTypeCapability]'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "supported_storage_editions": {"key": "supportedStorageEditions", "type": "[StorageEditionCapability]"}, + "supported_server_versions": {"key": "supportedServerVersions", "type": "[ServerVersionCapability]"}, + "supported_node_types": {"key": "supportedNodeTypes", "type": "[NodeTypeCapability]"}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(HyperscaleNodeEditionCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.supported_storage_editions = None self.supported_server_versions = None @@ -807,7 +1214,7 @@ def __init__( self.status = None -class MaintenanceWindow(msrest.serialization.Model): +class MaintenanceWindow(_serialization.Model): """Maintenance window properties of a server. :ivar custom_window: indicates whether custom window is enabled or disabled. @@ -821,19 +1228,19 @@ 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__( self, *, - custom_window: Optional[str] = "Disabled", - start_hour: Optional[int] = 0, - start_minute: Optional[int] = 0, - day_of_week: Optional[int] = 0, + custom_window: str = "Disabled", + start_hour: int = 0, + start_minute: int = 0, + day_of_week: int = 0, **kwargs ): """ @@ -846,105 +1253,75 @@ 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(CheckNameAvailabilityResponse): """Represents a resource name availability. Variables are only populated by the server, and will be ignored when sending a request. - :ivar message: Error Message. - :vartype message: str - :ivar name_available: Indicates whether the resource name is available. + :ivar name_available: Indicates if the resource name is available. :vartype name_available: bool + :ivar reason: The reason why the given name is not available. Known values are: "Invalid" and + "AlreadyExists". + :vartype reason: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityReason + :ivar message: Detailed reason why the given name is available. + :vartype message: str :ivar name: name of the PostgreSQL server. :vartype name: str :ivar type: type of the server. :vartype type: str - :ivar reason: The name availability reason. Known values are: "Invalid", "AlreadyExists". - :vartype reason: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Reason """ _validation = { - 'message': {'readonly': True}, - 'name_available': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'reason': {'readonly': True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( self, + *, + name_available: Optional[bool] = None, + reason: Optional[Union[str, "_models.CheckNameAvailabilityReason"]] = None, + message: Optional[str] = None, **kwargs ): """ + :keyword name_available: Indicates if the resource name is available. + :paramtype name_available: bool + :keyword reason: The reason why the given name is not available. Known values are: "Invalid" + and "AlreadyExists". + :paramtype reason: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityReason + :keyword message: Detailed reason why the given name is available. + :paramtype message: str """ - super(NameAvailability, self).__init__(**kwargs) - self.message = None - self.name_available = None + super().__init__(name_available=name_available, reason=reason, message=message, **kwargs) self.name = None self.type = None - self.reason = None - - -class NameAvailabilityRequest(msrest.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. - :vartype name: str - :ivar type: Resource type used for verification. - :vartype type: str - """ - - _validation = { - 'name': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - *, - name: str, - type: Optional[str] = None, - **kwargs - ): - """ - :keyword name: Required. Resource name to verify. - :paramtype name: str - :keyword type: Resource type used for verification. - :paramtype type: str - """ - super(NameAvailabilityRequest, self).__init__(**kwargs) - self.name = name - self.type = type -class Network(msrest.serialization.Model): +class Network(_serialization.Model): """Network properties of a server. Variables are only populated by the server, and will be ignored when sending a request. :ivar public_network_access: public network access is enabled or not. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerPublicNetworkAccessState :ivar delegated_subnet_resource_id: delegated subnet arm resource id. @@ -954,35 +1331,29 @@ 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_arm_resource_id': {'key': 'privateDnsZoneArmResourceId', 'type': 'str'}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "delegated_subnet_resource_id": {"key": "delegatedSubnetResourceId", "type": "str"}, + "private_dns_zone_arm_resource_id": {"key": "privateDnsZoneArmResourceId", "type": "str"}, } - def __init__( - self, - *, - delegated_subnet_resource_id: Optional[str] = "", - private_dns_zone_arm_resource_id: Optional[str] = "", - **kwargs - ): + def __init__(self, *, delegated_subnet_resource_id: str = "", private_dns_zone_arm_resource_id: str = "", **kwargs): """ :keyword delegated_subnet_resource_id: delegated subnet arm resource id. :paramtype delegated_subnet_resource_id: str :keyword private_dns_zone_arm_resource_id: private dns zone arm resource id. :paramtype private_dns_zone_arm_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_arm_resource_id = private_dns_zone_arm_resource_id -class NodeTypeCapability(msrest.serialization.Model): +class NodeTypeCapability(_serialization.Model): """node type capability. Variables are only populated by the server, and will be ignored when sending a request. @@ -996,30 +1367,26 @@ class NodeTypeCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'node_type': {'readonly': True}, - 'status': {'readonly': True}, + "name": {"readonly": True}, + "node_type": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'node_type': {'key': 'nodeType', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "node_type": {"key": "nodeType", "type": "str"}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(NodeTypeCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.node_type = None self.status = None -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. @@ -1031,38 +1398,33 @@ class Operation(msrest.serialization.Model): :ivar is_data_action: Indicates whether the operation is a data action. :vartype is_data_action: bool :ivar origin: The intended executor of the operation. Known values are: "NotSpecified", "user", - "system". + and "system". :vartype origin: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.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'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{object}'}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "{object}"}, } - def __init__( - self, - *, - is_data_action: Optional[bool] = None, - **kwargs - ): + def __init__(self, *, is_data_action: Optional[bool] = None, **kwargs): """ :keyword is_data_action: Indicates whether the operation is a data action. :paramtype is_data_action: bool """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = None self.display = None self.is_data_action = is_data_action @@ -1070,7 +1432,7 @@ def __init__( 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. @@ -1086,33 +1448,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: Collection of available operation details. @@ -1123,17 +1481,11 @@ 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.postgresql_flexibleservers.models.Operation] @@ -1141,24 +1493,24 @@ def __init__( It's null for now, added for future use. :paramtype next_link: str """ - super(OperationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class RestartParameter(msrest.serialization.Model): +class RestartParameter(_serialization.Model): """Represents server restart parameters. :ivar restart_with_failover: Indicates whether to restart the server with failover. :vartype restart_with_failover: bool :ivar failover_mode: Failover mode. Known values are: "PlannedFailover", "ForcedFailover", - "PlannedSwitchover", "ForcedSwitchover". + "PlannedSwitchover", and "ForcedSwitchover". :vartype failover_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FailoverMode """ _attribute_map = { - 'restart_with_failover': {'key': 'restartWithFailover', 'type': 'bool'}, - 'failover_mode': {'key': 'failoverMode', 'type': 'str'}, + "restart_with_failover": {"key": "restartWithFailover", "type": "bool"}, + "failover_mode": {"key": "failoverMode", "type": "str"}, } def __init__( @@ -1172,11 +1524,11 @@ def __init__( :keyword restart_with_failover: Indicates whether to restart the server with failover. :paramtype restart_with_failover: bool :keyword failover_mode: Failover mode. Known values are: "PlannedFailover", "ForcedFailover", - "PlannedSwitchover", "ForcedSwitchover". + "PlannedSwitchover", and "ForcedSwitchover". :paramtype failover_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.FailoverMode """ - super(RestartParameter, self).__init__(**kwargs) + super().__init__(**kwargs) self.restart_with_failover = restart_with_failover self.failover_mode = failover_mode @@ -1196,46 +1548,45 @@ 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 system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :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}, + "system_data": {"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"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "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. @@ -1250,31 +1601,38 @@ 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 system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :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 sku: The SKU (pricing tier) of the server. :vartype sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku - :ivar system_data: The system metadata relating to this resource. - :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData + :ivar identity: Describes the identity of the application. + :vartype identity: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.UserAssignedIdentity :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 administrator_login_password: The administrator login password (required for server creation). :vartype administrator_login_password: str - :ivar version: PostgreSQL Server version. Known values are: "14", "13", "12", "11". + :ivar version: PostgreSQL Server version. Known values are: "14", "13", "12", and "11". :vartype version: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersion :ivar minor_version: The minor version of the server. :vartype minor_version: str :ivar state: A state of a server that is visible to user. Known values are: "Ready", - "Dropping", "Disabled", "Starting", "Stopping", "Stopped", "Updating". + "Dropping", "Disabled", "Starting", "Stopping", "Stopped", and "Updating". :vartype state: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerState :ivar fully_qualified_domain_name: The fully qualified domain name of a server. :vartype fully_qualified_domain_name: str :ivar storage: Storage properties of a server. :vartype storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage + :ivar auth_config: AuthConfig properties of a server. + :vartype auth_config: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.AuthConfig + :ivar data_encryption: Data encryption properties of a server. + :vartype data_encryption: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.DataEncryption :ivar backup: Backup properties of a server. :vartype backup: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Backup :ivar network: Network properties of a server. @@ -1286,91 +1644,114 @@ class Server(TrackedResource): :vartype maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow :ivar source_server_resource_id: The source server resource ID to restore from. It's required - when 'createMode' is 'PointInTimeRestore'. + when 'createMode' is 'PointInTimeRestore' or 'GeoRestore' or 'Replica'. :vartype source_server_resource_id: str :ivar point_in_time_utc: Restore point creation time (ISO8601 format), specifying the time to - restore from. It's required when 'createMode' is 'PointInTimeRestore'. + restore from. It's required when 'createMode' is 'PointInTimeRestore' or 'GeoRestore'. :vartype point_in_time_utc: ~datetime.datetime :ivar availability_zone: availability zone information of the server. :vartype availability_zone: str + :ivar replication_role: Replication role of the server. Known values are: "Primary", + "Secondary", "WalReplica", "SyncReplica", "AsyncReplica", "GeoSyncReplica", and + "GeoAsyncReplica". + :vartype replication_role: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ReplicationRole + :ivar replica_capacity: Replicas allowed for a server. + :vartype replica_capacity: int :ivar create_mode: The mode to create a new PostgreSQL server. Known values are: "Default", - "Create", "Update", "PointInTimeRestore". + "Create", "Update", "PointInTimeRestore", "GeoRestore", and "Replica". :vartype create_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateMode """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'system_data': {'readonly': True}, - 'minor_version': {'readonly': True}, - 'state': {'readonly': True}, - 'fully_qualified_domain_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "location": {"required": True}, + "minor_version": {"readonly": True}, + "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'}, - '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'}, - 'minor_version': {'key': 'properties.minorVersion', 'type': 'str'}, - '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'}, - 'network': {'key': 'properties.network', 'type': 'Network'}, - 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, - 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, - 'source_server_resource_id': {'key': 'properties.sourceServerResourceId', 'type': 'str'}, - 'point_in_time_utc': {'key': 'properties.pointInTimeUTC', 'type': 'iso-8601'}, - 'availability_zone': {'key': 'properties.availabilityZone', 'type': 'str'}, - 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, - } - - def __init__( + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "Sku"}, + "identity": {"key": "identity", "type": "UserAssignedIdentity"}, + "administrator_login": {"key": "properties.administratorLogin", "type": "str"}, + "administrator_login_password": {"key": "properties.administratorLoginPassword", "type": "str"}, + "version": {"key": "properties.version", "type": "str"}, + "minor_version": {"key": "properties.minorVersion", "type": "str"}, + "state": {"key": "properties.state", "type": "str"}, + "fully_qualified_domain_name": {"key": "properties.fullyQualifiedDomainName", "type": "str"}, + "storage": {"key": "properties.storage", "type": "Storage"}, + "auth_config": {"key": "properties.authConfig", "type": "AuthConfig"}, + "data_encryption": {"key": "properties.dataEncryption", "type": "DataEncryption"}, + "backup": {"key": "properties.backup", "type": "Backup"}, + "network": {"key": "properties.network", "type": "Network"}, + "high_availability": {"key": "properties.highAvailability", "type": "HighAvailability"}, + "maintenance_window": {"key": "properties.maintenanceWindow", "type": "MaintenanceWindow"}, + "source_server_resource_id": {"key": "properties.sourceServerResourceId", "type": "str"}, + "point_in_time_utc": {"key": "properties.pointInTimeUTC", "type": "iso-8601"}, + "availability_zone": {"key": "properties.availabilityZone", "type": "str"}, + "replication_role": {"key": "properties.replicationRole", "type": "str"}, + "replica_capacity": {"key": "properties.replicaCapacity", "type": "int"}, + "create_mode": {"key": "properties.createMode", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, location: str, tags: Optional[Dict[str, str]] = None, sku: Optional["_models.Sku"] = None, + identity: Optional["_models.UserAssignedIdentity"] = None, administrator_login: Optional[str] = None, administrator_login_password: Optional[str] = None, version: Optional[Union[str, "_models.ServerVersion"]] = None, storage: Optional["_models.Storage"] = None, + auth_config: Optional["_models.AuthConfig"] = None, + data_encryption: Optional["_models.DataEncryption"] = None, backup: Optional["_models.Backup"] = None, network: Optional["_models.Network"] = None, high_availability: Optional["_models.HighAvailability"] = None, maintenance_window: Optional["_models.MaintenanceWindow"] = None, source_server_resource_id: Optional[str] = None, point_in_time_utc: Optional[datetime.datetime] = None, - availability_zone: Optional[str] = "", + availability_zone: str = "", + replication_role: Optional[Union[str, "_models.ReplicationRole"]] = None, + replica_capacity: Optional[int] = None, create_mode: Optional[Union[str, "_models.CreateMode"]] = 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 :keyword sku: The SKU (pricing tier) of the server. :paramtype sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku + :keyword identity: Describes the identity of the application. + :paramtype identity: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.UserAssignedIdentity :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 administrator_login_password: The administrator login password (required for server creation). :paramtype administrator_login_password: str - :keyword version: PostgreSQL Server version. Known values are: "14", "13", "12", "11". + :keyword version: PostgreSQL Server version. Known values are: "14", "13", "12", and "11". :paramtype version: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersion :keyword storage: Storage properties of a server. :paramtype storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage + :keyword auth_config: AuthConfig properties of a server. + :paramtype auth_config: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.AuthConfig + :keyword data_encryption: Data encryption properties of a server. + :paramtype data_encryption: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.DataEncryption :keyword backup: Backup properties of a server. :paramtype backup: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Backup :keyword network: Network properties of a server. @@ -1382,20 +1763,27 @@ def __init__( :paramtype maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow :keyword source_server_resource_id: The source server resource ID to restore from. It's - required when 'createMode' is 'PointInTimeRestore'. + required when 'createMode' is 'PointInTimeRestore' or 'GeoRestore' or 'Replica'. :paramtype source_server_resource_id: str :keyword point_in_time_utc: Restore point creation time (ISO8601 format), specifying the time - to restore from. It's required when 'createMode' is 'PointInTimeRestore'. + to restore from. It's required when 'createMode' is 'PointInTimeRestore' or 'GeoRestore'. :paramtype point_in_time_utc: ~datetime.datetime :keyword availability_zone: availability zone information of the server. :paramtype availability_zone: str + :keyword replication_role: Replication role of the server. Known values are: "Primary", + "Secondary", "WalReplica", "SyncReplica", "AsyncReplica", "GeoSyncReplica", and + "GeoAsyncReplica". + :paramtype replication_role: str or + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ReplicationRole + :keyword replica_capacity: Replicas allowed for a server. + :paramtype replica_capacity: int :keyword create_mode: The mode to create a new PostgreSQL server. Known values are: "Default", - "Create", "Update", "PointInTimeRestore". + "Create", "Update", "PointInTimeRestore", "GeoRestore", and "Replica". :paramtype create_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateMode """ - super(Server, self).__init__(tags=tags, location=location, **kwargs) + super().__init__(tags=tags, location=location, **kwargs) self.sku = sku - self.system_data = None + self.identity = identity self.administrator_login = administrator_login self.administrator_login_password = administrator_login_password self.version = version @@ -1403,6 +1791,8 @@ def __init__( self.state = None self.fully_qualified_domain_name = None self.storage = storage + self.auth_config = auth_config + self.data_encryption = data_encryption self.backup = backup self.network = network self.high_availability = high_availability @@ -1410,6 +1800,8 @@ def __init__( self.source_server_resource_id = source_server_resource_id self.point_in_time_utc = point_in_time_utc self.availability_zone = availability_zone + self.replication_role = replication_role + self.replica_capacity = replica_capacity self.create_mode = create_mode @@ -1426,10 +1818,11 @@ class ServerBackup(ProxyResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar system_data: The system metadata relating to this resource. + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. :vartype system_data: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SystemData - :ivar backup_type: Backup type. - :vartype backup_type: str + :ivar backup_type: Backup type. "Full" + :vartype backup_type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Origin :ivar completed_time: Backup completed time (ISO8601 format). :vartype completed_time: ~datetime.datetime :ivar source: Backup source. @@ -1437,46 +1830,45 @@ 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__( self, *, - backup_type: Optional[str] = None, + backup_type: Optional[Union[str, "_models.Origin"]] = None, completed_time: Optional[datetime.datetime] = None, source: Optional[str] = None, **kwargs ): """ - :keyword backup_type: Backup type. - :paramtype backup_type: str + :keyword backup_type: Backup type. "Full" + :paramtype backup_type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Origin :keyword completed_time: Backup completed time (ISO8601 format). :paramtype completed_time: ~datetime.datetime :keyword source: Backup source. :paramtype source: str """ - super(ServerBackup, self).__init__(**kwargs) - self.system_data = None + super().__init__(**kwargs) 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. @@ -1486,16 +1878,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. @@ -1503,22 +1891,24 @@ 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 ServerForUpdate(msrest.serialization.Model): +class ServerForUpdate(_serialization.Model): # pylint: disable=too-many-instance-attributes """Represents a server to be updated. - :ivar location: The location the resource resides in. - :vartype location: str :ivar sku: The SKU (pricing tier) of the server. :vartype sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku - :ivar tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :ivar identity: Describes the identity of the application. + :vartype identity: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.UserAssignedIdentity + :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: PostgreSQL Server version. Known values are: "14", "13", "12", and "11". + :vartype version: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersion :ivar storage: Storage properties of a server. :vartype storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage :ivar backup: Backup properties of a server. @@ -1529,47 +1919,59 @@ class ServerForUpdate(msrest.serialization.Model): :ivar maintenance_window: Maintenance window properties of a server. :vartype maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow - :ivar create_mode: The mode to update a new PostgreSQL server. Known values are: "Default", + :ivar auth_config: AuthConfig properties of a server. + :vartype auth_config: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.AuthConfig + :ivar data_encryption: Data encryption properties of a server. + :vartype data_encryption: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.DataEncryption + :ivar create_mode: The mode to update a new PostgreSQL server. Known values are: "Default" and "Update". :vartype create_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateModeForUpdate """ _attribute_map = { - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'administrator_login_password': {'key': 'properties.administratorLoginPassword', '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'}, - 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, + "sku": {"key": "sku", "type": "Sku"}, + "identity": {"key": "identity", "type": "UserAssignedIdentity"}, + "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"}, + "auth_config": {"key": "properties.authConfig", "type": "AuthConfig"}, + "data_encryption": {"key": "properties.dataEncryption", "type": "DataEncryption"}, + "create_mode": {"key": "properties.createMode", "type": "str"}, } def __init__( self, *, - location: Optional[str] = None, sku: Optional["_models.Sku"] = None, + identity: Optional["_models.UserAssignedIdentity"] = None, tags: Optional[Dict[str, str]] = None, administrator_login_password: Optional[str] = None, + version: Optional[Union[str, "_models.ServerVersion"]] = None, storage: Optional["_models.Storage"] = None, backup: Optional["_models.Backup"] = None, high_availability: Optional["_models.HighAvailability"] = None, maintenance_window: Optional["_models.MaintenanceWindow"] = None, + auth_config: Optional["_models.AuthConfig"] = None, + data_encryption: Optional["_models.DataEncryption"] = None, create_mode: Optional[Union[str, "_models.CreateModeForUpdate"]] = None, **kwargs ): """ - :keyword location: The location the resource resides in. - :paramtype location: str :keyword sku: The SKU (pricing tier) of the server. :paramtype sku: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Sku - :keyword tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :keyword identity: Describes the identity of the application. + :paramtype identity: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.UserAssignedIdentity + :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: PostgreSQL Server version. Known values are: "14", "13", "12", and "11". + :paramtype version: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerVersion :keyword storage: Storage properties of a server. :paramtype storage: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Storage :keyword backup: Backup properties of a server. @@ -1580,24 +1982,31 @@ def __init__( :keyword maintenance_window: Maintenance window properties of a server. :paramtype maintenance_window: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.MaintenanceWindow - :keyword create_mode: The mode to update a new PostgreSQL server. Known values are: "Default", - "Update". + :keyword auth_config: AuthConfig properties of a server. + :paramtype auth_config: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.AuthConfig + :keyword data_encryption: Data encryption properties of a server. + :paramtype data_encryption: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.DataEncryption + :keyword create_mode: The mode to update a new PostgreSQL server. Known values are: "Default" + and "Update". :paramtype create_mode: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CreateModeForUpdate """ - super(ServerForUpdate, self).__init__(**kwargs) - self.location = location + super().__init__(**kwargs) self.sku = sku + self.identity = identity self.tags = tags self.administrator_login_password = administrator_login_password + self.version = version self.storage = storage self.backup = backup self.high_availability = high_availability self.maintenance_window = maintenance_window + self.auth_config = auth_config + self.data_encryption = data_encryption self.create_mode = create_mode -class ServerListResult(msrest.serialization.Model): +class ServerListResult(_serialization.Model): """A list of servers. :ivar value: The list of flexible servers. @@ -1607,35 +2016,31 @@ 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 flexible servers. :paramtype value: list[~azure.mgmt.rdbms.postgresql_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 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. :ivar name: server version. :vartype name: str + :ivar supported_versions_to_upgrade: Supported servers versions to upgrade. + :vartype supported_versions_to_upgrade: list[str] :ivar supported_vcores: :vartype supported_vcores: list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.VcoreCapability] @@ -1644,73 +2049,66 @@ class ServerVersionCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'supported_vcores': {'readonly': True}, - 'status': {'readonly': True}, + "name": {"readonly": True}, + "supported_versions_to_upgrade": {"readonly": True}, + "supported_vcores": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'supported_vcores': {'key': 'supportedVcores', 'type': '[VcoreCapability]'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "supported_versions_to_upgrade": {"key": "supportedVersionsToUpgrade", "type": "[str]"}, + "supported_vcores": {"key": "supportedVcores", "type": "[VcoreCapability]"}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ServerVersionCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None + self.supported_versions_to_upgrade = None self.supported_vcores = None self.status = None -class Sku(msrest.serialization.Model): +class Sku(_serialization.Model): """Sku 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. - Standard_D4s_v3. + :ivar name: The name of the sku, typically, tier + family + cores, e.g. Standard_D4s_v3. + Required. :vartype name: str - :ivar tier: Required. The tier of the particular SKU, e.g. Burstable. Known values are: - "Burstable", "GeneralPurpose", "MemoryOptimized". + :ivar tier: The tier of the particular SKU, e.g. Burstable. Required. Known values are: + "Burstable", "GeneralPurpose", and "MemoryOptimized". :vartype tier: str or ~azure.mgmt.rdbms.postgresql_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, typically, tier + family + cores, e.g. - Standard_D4s_v3. + :keyword name: The name of the sku, typically, tier + family + cores, e.g. Standard_D4s_v3. + Required. :paramtype name: str - :keyword tier: Required. The tier of the particular SKU, e.g. Burstable. Known values are: - "Burstable", "GeneralPurpose", "MemoryOptimized". + :keyword tier: The tier of the particular SKU, e.g. Burstable. Required. Known values are: + "Burstable", "GeneralPurpose", and "MemoryOptimized". :paramtype tier: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.SkuTier """ - super(Sku, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.tier = tier -class Storage(msrest.serialization.Model): +class Storage(_serialization.Model): """Storage properties of a server. :ivar storage_size_gb: Max storage allowed for a server. @@ -1718,24 +2116,19 @@ class Storage(msrest.serialization.Model): """ _attribute_map = { - 'storage_size_gb': {'key': 'storageSizeGB', 'type': 'int'}, + "storage_size_gb": {"key": "storageSizeGB", "type": "int"}, } - def __init__( - self, - *, - storage_size_gb: Optional[int] = None, - **kwargs - ): + def __init__(self, *, storage_size_gb: Optional[int] = None, **kwargs): """ :keyword storage_size_gb: Max storage allowed for a server. :paramtype storage_size_gb: int """ - super(Storage, self).__init__(**kwargs) + super().__init__(**kwargs) self.storage_size_gb = storage_size_gb -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. @@ -1750,30 +2143,26 @@ class StorageEditionCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'supported_storage_mb': {'readonly': True}, - 'status': {'readonly': True}, + "name": {"readonly": True}, + "supported_storage_mb": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'supported_storage_mb': {'key': 'supportedStorageMB', 'type': '[StorageMBCapability]'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "supported_storage_mb": {"key": "supportedStorageMB", "type": "[StorageMBCapability]"}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(StorageEditionCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.supported_storage_mb = None self.status = None -class StorageMBCapability(msrest.serialization.Model): +class StorageMBCapability(_serialization.Model): """storage size in MB capability. Variables are only populated by the server, and will be ignored when sending a request. @@ -1781,47 +2170,92 @@ class StorageMBCapability(msrest.serialization.Model): :ivar name: storage MB name. :vartype name: str :ivar supported_iops: supported IOPS. - :vartype supported_iops: long + :vartype supported_iops: int :ivar storage_size_mb: storage size in MB. - :vartype storage_size_mb: long + :vartype storage_size_mb: int + :ivar supported_upgradable_tier_list: + :vartype supported_upgradable_tier_list: + list[~azure.mgmt.rdbms.postgresql_flexibleservers.models.StorageTierCapability] :ivar status: The status. :vartype status: str """ _validation = { - 'name': {'readonly': True}, - 'supported_iops': {'readonly': True}, - 'storage_size_mb': {'readonly': True}, - 'status': {'readonly': True}, + "name": {"readonly": True}, + "supported_iops": {"readonly": True}, + "storage_size_mb": {"readonly": True}, + "supported_upgradable_tier_list": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, - 'storage_size_mb': {'key': 'storageSizeMB', 'type': 'long'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "supported_iops": {"key": "supportedIops", "type": "int"}, + "storage_size_mb": {"key": "storageSizeMB", "type": "int"}, + "supported_upgradable_tier_list": {"key": "supportedUpgradableTierList", "type": "[StorageTierCapability]"}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(StorageMBCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.supported_iops = None self.storage_size_mb = None + self.supported_upgradable_tier_list = None + self.status = None + + +class StorageTierCapability(_serialization.Model): + """StorageTierCapability. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: Name to represent Storage tier capability. + :vartype name: str + :ivar tier_name: Storage tier name. + :vartype tier_name: str + :ivar iops: Supported IOPS for this storage tier. + :vartype iops: int + :ivar is_baseline: Indicates if this is a baseline storage tier or not. + :vartype is_baseline: bool + :ivar status: Status os this storage tier. + :vartype status: str + """ + + _validation = { + "name": {"readonly": True}, + "tier_name": {"readonly": True}, + "iops": {"readonly": True}, + "is_baseline": {"readonly": True}, + "status": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "tier_name": {"key": "tierName", "type": "str"}, + "iops": {"key": "iops", "type": "int"}, + "is_baseline": {"key": "isBaseline", "type": "bool"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.name = None + self.tier_name = None + self.iops = None + self.is_baseline = None self.status = 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.postgresql_flexibleservers.models.CreatedByType :ivar created_at: The timestamp of resource creation (UTC). @@ -1829,7 +2263,7 @@ class SystemData(msrest.serialization.Model): :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.postgresql_flexibleservers.models.CreatedByType :ivar last_modified_at: The timestamp of resource last modification (UTC). @@ -1837,12 +2271,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__( @@ -1860,7 +2294,7 @@ 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.postgresql_flexibleservers.models.CreatedByType :keyword created_at: The timestamp of resource creation (UTC). @@ -1868,13 +2302,13 @@ def __init__( :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.postgresql_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 @@ -1883,7 +2317,80 @@ def __init__( self.last_modified_at = last_modified_at -class VcoreCapability(msrest.serialization.Model): +class UserAssignedIdentity(_serialization.Model): + """Information describing the identities associated with this application. + + All required parameters must be populated in order to send to Azure. + + :ivar user_assigned_identities: represents user assigned identities map. + :vartype user_assigned_identities: dict[str, + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.UserIdentity] + :ivar type: the types of identities associated with this resource; currently restricted to + 'SystemAssigned and UserAssigned'. Required. Known values are: "None", "SystemAssigned", and + "UserAssigned". + :vartype type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.IdentityType + """ + + _validation = { + "type": {"required": True}, + } + + _attribute_map = { + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserIdentity}"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, + *, + type: Union[str, "_models.IdentityType"], + user_assigned_identities: Optional[Dict[str, "_models.UserIdentity"]] = None, + **kwargs + ): + """ + :keyword user_assigned_identities: represents user assigned identities map. + :paramtype user_assigned_identities: dict[str, + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.UserIdentity] + :keyword type: the types of identities associated with this resource; currently restricted to + 'SystemAssigned and UserAssigned'. Required. Known values are: "None", "SystemAssigned", and + "UserAssigned". + :paramtype type: str or ~azure.mgmt.rdbms.postgresql_flexibleservers.models.IdentityType + """ + super().__init__(**kwargs) + self.user_assigned_identities = user_assigned_identities + self.type = type + + +class UserIdentity(_serialization.Model): + """Describes a single user-assigned identity associated with the application. + + :ivar principal_id: the object identifier of the Service Principal which this identity + represents. + :vartype principal_id: str + :ivar client_id: the client identifier of the Service Principal which this identity represents. + :vartype client_id: str + """ + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, *, principal_id: Optional[str] = None, client_id: Optional[str] = None, **kwargs): + """ + :keyword principal_id: the object identifier of the Service Principal which this identity + represents. + :paramtype principal_id: str + :keyword client_id: the client identifier of the Service Principal which this identity + represents. + :paramtype client_id: str + """ + super().__init__(**kwargs) + self.principal_id = principal_id + self.client_id = client_id + + +class VcoreCapability(_serialization.Model): """Vcores capability. Variables are only populated by the server, and will be ignored when sending a request. @@ -1891,38 +2398,34 @@ class VcoreCapability(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_vcore_mb: supported memory per vCore in MB. - :vartype supported_memory_per_vcore_mb: long + :vartype supported_memory_per_vcore_mb: int :ivar status: The status. :vartype status: str """ _validation = { - 'name': {'readonly': True}, - 'v_cores': {'readonly': True}, - 'supported_iops': {'readonly': True}, - 'supported_memory_per_vcore_mb': {'readonly': True}, - 'status': {'readonly': True}, + "name": {"readonly": True}, + "v_cores": {"readonly": True}, + "supported_iops": {"readonly": True}, + "supported_memory_per_vcore_mb": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'v_cores': {'key': 'vCores', 'type': 'long'}, - 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, - 'supported_memory_per_vcore_mb': {'key': 'supportedMemoryPerVcoreMB', 'type': 'long'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "v_cores": {"key": "vCores", "type": "int"}, + "supported_iops": {"key": "supportedIops", "type": "int"}, + "supported_memory_per_vcore_mb": {"key": "supportedMemoryPerVcoreMB", "type": "int"}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(VcoreCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.v_cores = None self.supported_iops = None @@ -1930,7 +2433,7 @@ def __init__( self.status = None -class VirtualNetworkSubnetUsageParameter(msrest.serialization.Model): +class VirtualNetworkSubnetUsageParameter(_serialization.Model): """Virtual network subnet usage parameter. :ivar virtual_network_arm_resource_id: Virtual network resource id. @@ -1938,24 +2441,19 @@ class VirtualNetworkSubnetUsageParameter(msrest.serialization.Model): """ _attribute_map = { - 'virtual_network_arm_resource_id': {'key': 'virtualNetworkArmResourceId', 'type': 'str'}, + "virtual_network_arm_resource_id": {"key": "virtualNetworkArmResourceId", "type": "str"}, } - def __init__( - self, - *, - virtual_network_arm_resource_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, virtual_network_arm_resource_id: Optional[str] = None, **kwargs): """ :keyword virtual_network_arm_resource_id: Virtual network resource id. :paramtype virtual_network_arm_resource_id: str """ - super(VirtualNetworkSubnetUsageParameter, self).__init__(**kwargs) + super().__init__(**kwargs) self.virtual_network_arm_resource_id = virtual_network_arm_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. @@ -1970,24 +2468,20 @@ class VirtualNetworkSubnetUsageResult(msrest.serialization.Model): """ _validation = { - 'delegated_subnets_usage': {'readonly': True}, - 'location': {'readonly': True}, - 'subscription_id': {'readonly': True}, + "delegated_subnets_usage": {"readonly": True}, + "location": {"readonly": True}, + "subscription_id": {"readonly": True}, } _attribute_map = { - '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]"}, + "location": {"key": "location", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(VirtualNetworkSubnetUsageResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.delegated_subnets_usage = None self.location = None self.subscription_id = None diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_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/postgresql_flexibleservers/models/_postgre_sql_management_client_enums.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_postgre_sql_management_client_enums.py index 7c2cc9d664ca..c29935f80eb7 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_postgre_sql_management_client_enums.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/models/_postgre_sql_management_client_enums.py @@ -10,82 +10,127 @@ from azure.core import CaseInsensitiveEnumMeta +class ArmServerKeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Data encryption type to depict if it is System assigned vs Azure Key vault.""" + + SYSTEM_ASSIGNED = "SystemAssigned" + AZURE_KEY_VAULT = "AzureKeyVault" + + +class CheckNameAvailabilityReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The reason why the given name is not available.""" + + INVALID = "Invalid" + ALREADY_EXISTS = "AlreadyExists" + + class ConfigurationDataType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Data type of the configuration. - """ + """Data type of the configuration.""" BOOLEAN = "Boolean" NUMERIC = "Numeric" INTEGER = "Integer" ENUMERATION = "Enumeration" + 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 PostgreSQL server. - """ + """The mode to create a new PostgreSQL server.""" DEFAULT = "Default" CREATE = "Create" UPDATE = "Update" POINT_IN_TIME_RESTORE = "PointInTimeRestore" + GEO_RESTORE = "GeoRestore" + REPLICA = "Replica" + class CreateModeForUpdate(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The mode to update a new PostgreSQL server. - """ + """The mode to update a new PostgreSQL server.""" DEFAULT = "Default" UPDATE = "Update" + class FailoverMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Failover mode. - """ + """Failover mode.""" PLANNED_FAILOVER = "PlannedFailover" FORCED_FAILOVER = "ForcedFailover" PLANNED_SWITCHOVER = "PlannedSwitchover" FORCED_SWITCHOVER = "ForcedSwitchover" + class GeoRedundantBackupEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """A value indicating whether Geo-Redundant backup is enabled on the server. - """ + """A value indicating whether Geo-Redundant backup is enabled on the server.""" ENABLED = "Enabled" DISABLED = "Disabled" + class HighAvailabilityMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The HA mode for the server. - """ + """The HA mode for the server.""" DISABLED = "Disabled" ZONE_REDUNDANT = "ZoneRedundant" SAME_ZONE = "SameZone" -class OperationOrigin(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The intended executor of the operation. + +class IdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """the types of identities associated with this resource; currently restricted to 'SystemAssigned + and UserAssigned'. """ + NONE = "None" + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + + +class OperationOrigin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation.""" + NOT_SPECIFIED = "NotSpecified" USER = "user" SYSTEM = "system" -class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The name availability reason. - """ - INVALID = "Invalid" - ALREADY_EXISTS = "AlreadyExists" +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Backup type.""" + + FULL = "Full" + + +class PrincipalType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The principal type used to represent the type of Active Directory Administrator.""" + + UNKNOWN = "Unknown" + USER = "User" + GROUP = "Group" + SERVICE_PRINCIPAL = "ServicePrincipal" + + +class ReplicationRole(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Used to indicate role of the server in replication set.""" + + PRIMARY = "Primary" + SECONDARY = "Secondary" + WAL_REPLICA = "WalReplica" + SYNC_REPLICA = "SyncReplica" + ASYNC_REPLICA = "AsyncReplica" + GEO_SYNC_REPLICA = "GeoSyncReplica" + GEO_ASYNC_REPLICA = "GeoAsyncReplica" + class ServerHAState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """A state of a HA server that is visible to user. - """ + """A state of a HA server that is visible to user.""" NOT_ENABLED = "NotEnabled" CREATING_STANDBY = "CreatingStandby" @@ -94,16 +139,16 @@ class ServerHAState(str, Enum, metaclass=CaseInsensitiveEnumMeta): HEALTHY = "Healthy" REMOVING_STANDBY = "RemovingStandby" + class ServerPublicNetworkAccessState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """public network access is enabled or not - """ + """public network access is enabled or not.""" 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" @@ -113,18 +158,18 @@ 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.""" FOURTEEN = "14" THIRTEEN = "13" TWELVE = "12" ELEVEN = "11" + class SkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The tier of the particular SKU, e.g. Burstable. - """ + """The tier of the particular SKU, e.g. Burstable.""" BURSTABLE = "Burstable" GENERAL_PURPOSE = "GeneralPurpose" diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/__init__.py index 2cb2a786e327..0e78e3303939 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/__init__.py @@ -6,31 +6,36 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._databases_operations import DatabasesOperations -from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations -from ._servers_operations import ServersOperations +from ._administrators_operations import AdministratorsOperations from ._backups_operations import BackupsOperations -from ._firewall_rules_operations import FirewallRulesOperations -from ._configurations_operations import ConfigurationsOperations -from ._check_name_availability_operations import CheckNameAvailabilityOperations from ._location_based_capabilities_operations import LocationBasedCapabilitiesOperations -from ._virtual_network_subnet_usage_operations import VirtualNetworkSubnetUsageOperations +from ._check_name_availability_operations import CheckNameAvailabilityOperations +from ._check_name_availability_with_location_operations import CheckNameAvailabilityWithLocationOperations +from ._configurations_operations import ConfigurationsOperations +from ._databases_operations import DatabasesOperations +from ._firewall_rules_operations import FirewallRulesOperations +from ._servers_operations import ServersOperations from ._operations import Operations +from ._get_private_dns_zone_suffix_operations import GetPrivateDnsZoneSuffixOperations +from ._virtual_network_subnet_usage_operations import VirtualNetworkSubnetUsageOperations 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__ = [ - 'DatabasesOperations', - 'GetPrivateDnsZoneSuffixOperations', - 'ServersOperations', - 'BackupsOperations', - 'FirewallRulesOperations', - 'ConfigurationsOperations', - 'CheckNameAvailabilityOperations', - 'LocationBasedCapabilitiesOperations', - 'VirtualNetworkSubnetUsageOperations', - 'Operations', + "AdministratorsOperations", + "BackupsOperations", + "LocationBasedCapabilitiesOperations", + "CheckNameAvailabilityOperations", + "CheckNameAvailabilityWithLocationOperations", + "ConfigurationsOperations", + "DatabasesOperations", + "FirewallRulesOperations", + "ServersOperations", + "Operations", + "GetPrivateDnsZoneSuffixOperations", + "VirtualNetworkSubnetUsageOperations", ] __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/postgresql_flexibleservers/operations/_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_administrators_operations.py new file mode 100644 index 000000000000..a1e6c2ec0bd9 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_administrators_operations.py @@ -0,0 +1,746 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_request( + resource_group_name: str, server_name: str, object_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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}", + ) # 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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "objectId": _SERIALIZER.url("object_id", object_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, object_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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}", + ) # 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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "objectId": _SERIALIZER.url("object_id", object_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + resource_group_name: str, server_name: str, object_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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}", + ) # 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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "objectId": _SERIALIZER.url("object_id", object_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_server_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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AdministratorsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.rdbms.postgresql_flexibleservers.PostgreSQLManagementClient`'s + :attr:`administrators` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _create_initial( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: Union[_models.ActiveDirectoryAdministratorAdd, IO], + **kwargs: Any + ) -> _models.ActiveDirectoryAdministrator: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ActiveDirectoryAdministrator] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ActiveDirectoryAdministratorAdd") + + request = build_create_request( + resource_group_name=resource_group_name, + server_name=server_name, + object_id=object_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ActiveDirectoryAdministrator", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ActiveDirectoryAdministrator", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @overload + def begin_create( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: _models.ActiveDirectoryAdministratorAdd, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ActiveDirectoryAdministrator]: + """Creates a new 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :param parameters: The required parameters for adding an active directory administrator for a + server. Required. + :type parameters: + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministratorAdd + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 ActiveDirectoryAdministrator or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ActiveDirectoryAdministrator]: + """Creates a new 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :param parameters: The required parameters for adding an active directory administrator for 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 ActiveDirectoryAdministrator or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + server_name: str, + object_id: str, + parameters: Union[_models.ActiveDirectoryAdministratorAdd, IO], + **kwargs: Any + ) -> LROPoller[_models.ActiveDirectoryAdministrator]: + """Creates a new 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :param parameters: The required parameters for adding an active directory administrator for a + server. Is either a model type or a IO type. Required. + :type parameters: + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministratorAdd or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 ActiveDirectoryAdministrator or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ActiveDirectoryAdministrator] + 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, + server_name=server_name, + object_id=object_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("ActiveDirectoryAdministrator", 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 + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, server_name: str, object_id: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + resource_group_name=resource_group_name, + server_name=server_name, + object_id=object_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if cls: + return cls(pipeline_response, None, response_headers) + + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @distributed_trace + def begin_delete( + self, resource_group_name: str, server_name: str, object_id: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes an Active Directory Administrator associated with the 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 object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + 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, + object_id=object_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, 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, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @distributed_trace + def get( + self, resource_group_name: str, server_name: str, object_id: str, **kwargs: Any + ) -> _models.ActiveDirectoryAdministrator: + """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. Required. + :type server_name: str + :param object_id: Guid of the objectId for the administrator. Required. + :type object_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ActiveDirectoryAdministrator or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ActiveDirectoryAdministrator] + + request = build_get_request( + resource_group_name=resource_group_name, + server_name=server_name, + object_id=object_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ActiveDirectoryAdministrator", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators/{objectId}"} # type: ignore + + @distributed_trace + def list_by_server( + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.ActiveDirectoryAdministrator"]: + """List all the AAD administrators 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. 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 ActiveDirectoryAdministrator or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ActiveDirectoryAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AdministratorListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_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"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AdministratorListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_backups_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_backups_operations.py index aebb1c68f081..7134469a789b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_backups_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_backups_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,87 +27,94 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/backups/{backupName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "backupName": _SERIALIZER.url("backup_name", backup_name, "str", min_length=1, pattern=r"^[-\w\._]+$"), } _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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/backups") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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: """ @@ -121,47 +135,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, - backup_name: str, - **kwargs: Any - ) -> _models.ServerBackup: - """List all the backups for a given server. + def get(self, resource_group_name: str, server_name: str, backup_name: str, **kwargs: Any) -> _models.ServerBackup: + """Get specific backup 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -169,65 +181,67 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_flexibleservers.models.ServerBackupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -235,15 +249,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 @@ -260,21 +276,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/backups"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/backups"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_operations.py index 95fbca19fea4..2220cc110d66 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_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, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, 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 +25,50 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability" + ) # pylint: disable=line-too-long 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,44 +89,97 @@ 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, + name_availability_request: _models.CheckNameAvailabilityRequest, + *, + 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.postgresql_flexibleservers.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default 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.postgresql_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 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.postgresql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def execute( + self, name_availability_request: Union[_models.CheckNameAvailabilityRequest, 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.postgresql_flexibleservers.models.NameAvailabilityRequest + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, "CheckNameAvailabilityRequest") 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 +187,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_with_location_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_with_location_operations.py new file mode 100644 index 000000000000..d2865fc1ef72 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_check_name_availability_with_location_operations.py @@ -0,0 +1,225 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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", min_length=1, pattern=r"^[-\w\._]+$"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class CheckNameAvailabilityWithLocationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.rdbms.postgresql_flexibleservers.PostgreSQLManagementClient`'s + :attr:`check_name_availability_with_location` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def execute( + self, + location_name: str, + name_availability_request: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param location_name: The name of the location. Required. + :type location_name: str + :param name_availability_request: The required parameters for checking if resource name is + available. Required. + :type name_availability_request: + ~azure.mgmt.rdbms.postgresql_flexibleservers.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default 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.postgresql_flexibleservers.models.NameAvailability + :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 resource. + + :param location_name: The name of the location. Required. + :type location_name: str + :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.postgresql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def execute( + self, + location_name: str, + name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], + **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param location_name: The name of the location. Required. + :type location_name: str + :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.postgresql_flexibleservers.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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.postgresql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] + + 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, "CheckNameAvailabilityRequest") + + request = build_execute_request( + location_name=location_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.execute.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("NameAvailability", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_configurations_operations.py index ca325181c6dd..c58d11d7600a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_configurations_operations.py @@ -6,11 +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, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,181 +29,182 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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( - 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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "configurationName": _SERIALIZER.url( + "configuration_name", configuration_name, "str", min_length=1, pattern=r"^[-\w\._]+$" + ), } _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_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 + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "configurationName": _SERIALIZER.url( + "configuration_name", configuration_name, "str", min_length=1, pattern=r"^[-\w\._]+$" + ), } _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_put_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 + _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_put_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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "configurationName": _SERIALIZER.url( + "configuration_name", configuration_name, "str", min_length=1, pattern=r"^[-\w\._]+$" + ), } _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 - ) + _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) + class ConfigurationsOperations: """ @@ -217,46 +225,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 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 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.postgresql_flexibleservers.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -264,15 +274,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 @@ -289,65 +301,63 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations"} # 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -355,57 +365,68 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore def _update_initial( self, resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.ConfigurationForUpdate, 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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Configuration') - - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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, "ConfigurationForUpdate") + + 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, ) @@ -413,27 +434,113 @@ 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]: + if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: _models.ConfigurationForUpdate, + *, + 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: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.ConfigurationForUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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.postgresql_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 + 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.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_update( @@ -441,19 +548,25 @@ def begin_update( resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.ConfigurationForUpdate, 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. + :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. - :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.Configuration + :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.postgresql_flexibleservers.models.ConfigurationForUpdate or + IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -466,20 +579,19 @@ def begin_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -488,71 +600,81 @@ 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, 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_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore def _put_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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Configuration') - - request = build_put_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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_put_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._put_initial.metadata['url'], + content=_content, + template_url=self._put_initial.metadata["url"], headers=_headers, params=_params, ) @@ -560,47 +682,138 @@ def _put_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]: + if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("Configuration", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _put_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + _put_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - - @distributed_trace + @overload def begin_put( 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.postgresql_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.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_put( + 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.postgresql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_put( + 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.postgresql_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 @@ -613,20 +826,19 @@ def begin_put( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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._put_initial( # type: ignore resource_group_name=resource_group_name, @@ -635,36 +847,34 @@ def begin_put( 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, 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_put.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_put.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_databases_operations.py index abc8ef092cd2..41530449fce6 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_databases_operations.py @@ -6,11 +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, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +29,173 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_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_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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str", min_length=1, pattern=r"^[-\w\._]+$"), } _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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str", min_length=1, pattern=r"^[-\w\._]+$"), } _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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "databaseName": _SERIALIZER.url("database_name", database_name, "str", min_length=1, pattern=r"^[-\w\._]+$"), } _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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 +216,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") - def _create_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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Database') - - request = build_create_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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_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_initial.metadata['url'], + content=_content, + template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) @@ -248,50 +266,59 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} 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 response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - @distributed_trace + @overload def begin_create( 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.postgresql_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 @@ -303,20 +330,96 @@ def begin_create( :return: An instance of LROPoller that returns either Database or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Database] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + 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.postgresql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + 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.postgresql_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 + 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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_initial( # type: ignore resource_group_name=resource_group_name, @@ -325,66 +428,64 @@ 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('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, 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_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -392,37 +493,37 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -434,97 +535,93 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -532,64 +629,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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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) + :return: An iterator like instance of either Database or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.DatabaseListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -597,15 +695,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 @@ -622,21 +722,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_firewall_rules_operations.py index ab36212bbf75..bba68160b574 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_firewall_rules_operations.py @@ -6,11 +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, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +29,179 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "firewallRuleName": _SERIALIZER.url( + "firewall_rule_name", firewall_rule_name, "str", min_length=1, pattern=r"^[-\w\._]+$" + ), } _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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "firewallRuleName": _SERIALIZER.url( + "firewall_rule_name", firewall_rule_name, "str", min_length=1, pattern=r"^[-\w\._]+$" + ), } _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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), + "firewallRuleName": _SERIALIZER.url( + "firewall_rule_name", firewall_rule_name, "str", min_length=1, pattern=r"^[-\w\._]+$" + ), } _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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 +222,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") - 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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'FirewallRule') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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( 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,50 +272,138 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} 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 response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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.postgresql_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 + 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.postgresql_flexibleservers.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.postgresql_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 @@ -304,20 +416,19 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +437,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('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, 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_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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,37 +502,37 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -435,97 +544,95 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: """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 - :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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +640,67 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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 PostgreSQL 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.postgresql_flexibleservers.models.FirewallRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +708,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,21 +735,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py index 87fe682657a2..9e5302a26a00 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_get_private_dns_zone_suffix_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,38 +25,40 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DBforPostgreSQL/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 +79,34 @@ 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 - ) -> str: + def execute(self, **kwargs: Any) -> str: """Get private DNS zone suffix in the cloud. :keyword callable cls: A custom type or function that will be passed the direct response - :return: str, or the result of cls(response) + :return: str or the result of cls(response) :rtype: str - :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', "2022-01-20-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[str] + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + cls = kwargs.pop("cls", None) # type: ClsType[str] - 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 +114,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('str', pipeline_response) + deserialized = self._deserialize("str", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/providers/Microsoft.DBforPostgreSQL/getPrivateDnsZoneSuffix"} # type: ignore - + execute.metadata = {"url": "/providers/Microsoft.DBforPostgreSQL/getPrivateDnsZoneSuffix"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_location_based_capabilities_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_location_based_capabilities_operations.py index 5e48de5a19b0..bfea773e7934 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_location_based_capabilities_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_location_based_capabilities_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,46 +27,49 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_execute_request( - subscription_id: str, - location_name: str, - **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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/capabilities") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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", min_length=1, pattern=r"^[-\w\._]+$"), } _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 +90,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 execute( - self, - location_name: str, - **kwargs: Any - ) -> Iterable[_models.CapabilitiesListResult]: + def execute(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.postgresql_flexibleservers.models.CapabilitiesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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_execute_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.execute.metadata['url'], + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -123,14 +134,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_execute_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,21 +161,18 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/capabilities"} # type: ignore + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/capabilities"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_operations.py index 2eadf4cb9feb..dbe7b31192a5 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_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. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,38 +25,40 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: + +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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DBforPostgreSQL/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,34 +79,34 @@ 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 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.postgresql_flexibleservers.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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -106,22 +114,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/operations"} # type: ignore - + list.metadata = {"url": "/providers/Microsoft.DBforPostgreSQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_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/postgresql_flexibleservers/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_servers_operations.py index 2fe56932b182..4dc244c9996d 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_servers_operations.py @@ -6,11 +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, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,362 +29,341 @@ 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') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ServerForUpdate] = None, - content: Any = None, - **kwargs: Any + +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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any +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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 - ) + _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: + +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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + 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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/flexibleServers") + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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 - ) + _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, - *, - json: Optional[_models.RestartParameter] = None, - content: Any = None, - **kwargs: Any +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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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) -def build_start_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + +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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 - ) + _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: + +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', "2022-01-20-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop( + "api_version", _params.pop("api-version", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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", max_length=63, min_length=3, pattern=r"^[a-z][a-z0-9]*$" + ), } _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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + class ServersOperations: """ @@ -398,36 +384,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") - 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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'Server') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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, ) @@ -435,47 +428,52 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('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.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. :param resource_group_name: The 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.postgresql_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 @@ -487,20 +485,86 @@ def begin_create( :return: An instance of LROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_flexibleservers.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :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. + + :param resource_group_name: The 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.postgresql_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. + + :param resource_group_name: The 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.postgresql_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 + 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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -508,69 +572,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, 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_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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]] - - _json = self._serialize.body(parameters, 'ServerForUpdate') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.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, "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, ) @@ -578,45 +648,54 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, response_headers) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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 @@ -628,20 +707,88 @@ def begin_update( :return: An instance of LROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.postgresql_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.postgresql_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.postgresql_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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -649,64 +796,63 @@ 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, 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_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -714,34 +860,33 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -753,92 +898,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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -846,60 +988,62 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/flexibleServers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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) + :return: An iterator like instance of either Server or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -907,14 +1051,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 @@ -931,55 +1078,55 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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) + :return: An iterator like instance of either Server or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -987,13 +1134,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 @@ -1010,57 +1161,66 @@ 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 if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/flexibleServers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/flexibleServers"} # type: ignore def _restart_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - parameters: Optional[_models.RestartParameter] = None, + parameters: Optional[Union[_models.RestartParameter, IO]] = None, **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', "2022-01-20-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] - - if parameters is not None: - _json = self._serialize.body(parameters, 'RestartParameter') + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters else: - _json = None + if parameters is not None: + _json = self._serialize.body(parameters, "RestartParameter") + else: + _json = 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, 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, ) @@ -1068,38 +1228,82 @@ 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]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _restart_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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: Optional[_models.RestartParameter] = None, + *, + 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 parameters for restarting a server. Default value is None. :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.RestartParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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: + """ + + @overload + def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: Optional[IO] = None, + *, + 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 parameters for restarting a server. Default value is None. + :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 @@ -1110,20 +1314,53 @@ 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: + """ + + @distributed_trace + def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: Optional[Union[_models.RestartParameter, IO]] = None, + **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 parameters for restarting a server. Is either a model type or a IO type. + Default value is None. + :type parameters: ~azure.mgmt.rdbms.postgresql_flexibleservers.models.RestartParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, @@ -1131,62 +1368,61 @@ 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, 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_restart.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -1194,34 +1430,33 @@ 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _start_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -1233,80 +1468,78 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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_start.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/start"} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, ) @@ -1314,34 +1547,33 @@ 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.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if cls: - return cls(pipeline_response, None, {}) + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - _stop_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop"} # type: ignore + if cls: + return cls(pipeline_response, None, response_headers) + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/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. @@ -1353,52 +1585,49 @@ 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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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, 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_stop.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop"} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/stop"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_virtual_network_subnet_usage_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_virtual_network_subnet_usage_operations.py index d3a4fe0366e3..5123bdba31cd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_virtual_network_subnet_usage_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql_flexibleservers/operations/_virtual_network_subnet_usage_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, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, 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 +25,52 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_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', "2022-01-20-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", "2022-03-08-preview") + ) # type: Literal["2022-03-08-preview"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/checkVirtualNetworkSubnetUsage") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/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", min_length=1, pattern=r"^[-\w\._]+$"), } _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 VirtualNetworkSubnetUsageOperations: """ @@ -87,47 +91,103 @@ 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.postgresql_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.postgresql_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.postgresql_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.postgresql_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.postgresql_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', "2022-01-20-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: Literal["2022-03-08-preview"] + 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 +195,21 @@ 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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, 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.DBforPostgreSQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/adds_an_active_directory_administrator_for_the_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/adds_an_active_directory_administrator_for_the_server.py new file mode 100644 index 000000000000..1434e5905c25 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/adds_an_active_directory_administrator_for_the_server.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python adds_an_active_directory_administrator_for_the_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.administrators.begin_create( + resource_group_name="testrg", + server_name="testserver", + object_id="oooooooo-oooo-oooo-oooo-oooooooooooo", + parameters={ + "properties": { + "principalName": "testuser1@microsoft.com", + "principalType": "User", + "tenantId": "tttttttt-tttt-tttt-tttt-tttttttttttt", + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/AdministratorAdd.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/administrator_delete.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/administrator_delete.py new file mode 100644 index 000000000000..1afeadaf9ed3 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/administrator_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python administrator_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.administrators.begin_delete( + resource_group_name="testrg", + server_name="testserver", + object_id="oooooooo-oooo-oooo-oooo-oooooooooooo", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/AdministratorDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/administrators_list_by_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/administrators_list_by_server.py new file mode 100644 index 000000000000..110502f45160 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/administrators_list_by_server.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python administrators_list_by_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.administrators.list_by_server( + resource_group_name="testrg", + server_name="pgtestsvc1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/AdministratorsListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/approve_or_reject_a_private_endpoint_connection_with_a_given_name..py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/approve_or_reject_a_private_endpoint_connection_with_a_given_name..py new file mode 100644 index 000000000000..2664424552bb --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/approve_or_reject_a_private_endpoint_connection_with_a_given_name..py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python approve_or_reject_a_private_endpoint_connection_with_a_given_name..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.private_endpoint_connections.begin_create_or_update( + resource_group_name="Default", + server_name="test-svr", + private_endpoint_connection_name="private-endpoint-connection-name", + parameters={ + "properties": { + "privateLinkServiceConnectionState": { + "description": "Approved by johndoe@contoso.com", + "status": "Approved", + } + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/capabilities_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/capabilities_list.py new file mode 100644 index 000000000000..e58e339996f5 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/capabilities_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python capabilities_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.location_based_capabilities.execute( + location_name="westus", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/CapabilitiesByLocation.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_create_or_update.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_create_or_update.py new file mode 100644 index 000000000000..c99866042768 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_create_or_update.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python configuration_create_or_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.configurations.begin_create_or_update( + resource_group_name="TestGroup", + server_name="testserver", + configuration_name="array_nulls", + parameters={"properties": {"source": "user-override", "value": "off"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ConfigurationCreateOrUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_get.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_get.py new file mode 100644 index 000000000000..6d88d709bfe5 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_get.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python configuration_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.configurations.get( + resource_group_name="TestGroup", + server_name="testserver", + configuration_name="array_nulls", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ConfigurationGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_list.py new file mode 100644 index 000000000000..7073d7782767 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/configuration_list.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python configuration_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.configurations.list_by_server( + resource_group_name="TestGroup", + server_name="testserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ConfigurationListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database.py new file mode 100644 index 000000000000..12ec5b6cee09 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_a_database.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.begin_create( + resource_group_name="TestGroup", + server_name="testserver", + database_name="db1", + parameters={"properties": {"charset": "utf8", "collation": "en_US.utf8"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/DatabaseCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database_as_a_georestore_in_geopaired_location.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database_as_a_georestore_in_geopaired_location.py new file mode 100644 index 000000000000..1fbdcb7ebcf3 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database_as_a_georestore_in_geopaired_location.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_a_database_as_a_georestore_in_geopaired_location.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="testrg", + server_name="pgtestsvc5geo", + parameters={ + "location": "eastus", + "properties": { + "createMode": "GeoRestore", + "pointInTimeUTC": "2021-06-27T00:04:59.4078005+00:00", + "sourceServerResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testrg/providers/Microsoft.DBforPostgreSQL/flexibleServers/sourcepgservername", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerCreateGeoRestore.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database_as_a_point_in_time_restore.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database_as_a_point_in_time_restore.py new file mode 100644 index 000000000000..e2414931f91d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_database_as_a_point_in_time_restore.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_a_database_as_a_point_in_time_restore.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="TargetResourceGroup", + server_name="targetserver", + parameters={ + "location": "brazilsouth", + "properties": { + "createMode": "PointInTimeRestore", + "restorePointInTime": "2017-12-14T00:00:37.467Z", + "sourceServerId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/SourceResourceGroup/providers/Microsoft.DBforPostgreSQL/servers/sourceserver", + }, + "sku": {"capacity": 2, "family": "Gen5", "name": "B_Gen5_2", "tier": "Basic"}, + "tags": {"ElasticServer": "1"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerCreatePointInTimeRestore.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_new_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_new_server.py new file mode 100644 index 000000000000..4d6df94e0a43 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_new_server.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_a_new_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="TestGroup", + server_name="pgtestsvc4", + parameters={ + "location": "westus", + "properties": { + "administratorLogin": "cloudsa", + "administratorLoginPassword": "", + "createMode": "Default", + "minimalTlsVersion": "TLS1_2", + "sslEnforcement": "Enabled", + "storageProfile": {"backupRetentionDays": 7, "geoRedundantBackup": "Disabled", "storageMB": 128000}, + }, + "sku": {"capacity": 2, "family": "Gen5", "name": "B_Gen5_2", "tier": "Basic"}, + "tags": {"ElasticServer": "1"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_new_server_with_active_directory_authentication_enabled.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_new_server_with_active_directory_authentication_enabled.py new file mode 100644 index 000000000000..62a2d6998d15 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_new_server_with_active_directory_authentication_enabled.py @@ -0,0 +1,62 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_a_new_server_with_active_directory_authentication_enabled.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="testrg", + server_name="pgtestsvc4", + parameters={ + "location": "westus", + "properties": { + "administratorLogin": "cloudsa", + "administratorLoginPassword": "password", + "authConfig": {"activeDirectoryAuthEnabled": True, "tenantId": "tttttt-tttt-tttt-tttt-tttttttttttt"}, + "availabilityZone": "1", + "backup": {"backupRetentionDays": 7, "geoRedundantBackup": "Disabled"}, + "createMode": "Create", + "dataEncryption": {"type": "SystemManaged"}, + "highAvailability": {"mode": "ZoneRedundant"}, + "network": { + "delegatedSubnetResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/test-vnet-subnet", + "privateDnsZoneArmResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/testrg/providers/Microsoft.Network/privateDnsZones/test-private-dns-zone.postgres.database.azure.com", + }, + "storage": {"storageSizeGB": 512}, + "version": "12", + }, + "sku": {"name": "Standard_D4s_v3", "tier": "GeneralPurpose"}, + "tags": {"ElasticServer": "1"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerCreateWithAadAuthEnabled.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_replica_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_replica_server.py new file mode 100644 index 000000000000..25091bfa1941 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_replica_server.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_a_replica_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="TestGroup_WestCentralUS", + server_name="testserver-replica1", + parameters={ + "location": "westcentralus", + "properties": { + "createMode": "Replica", + "sourceServerId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/TestGroup_WestCentralUS/providers/Microsoft.DBforPostgreSQL/servers/testserver-master", + }, + "sku": {"capacity": 2, "family": "Gen5", "name": "GP_Gen5_2", "tier": "GeneralPurpose"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerCreateReplicaMode.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_server_as_a_geo_restore_.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_server_as_a_geo_restore_.py new file mode 100644 index 000000000000..2993550e547d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_a_server_as_a_geo_restore_.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_a_server_as_a_geo_restore_.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="TargetResourceGroup", + server_name="targetserver", + parameters={ + "location": "westus", + "properties": { + "createMode": "GeoRestore", + "sourceServerId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/SourceResourceGroup/providers/Microsoft.DBforPostgreSQL/servers/sourceserver", + }, + "sku": {"capacity": 2, "family": "Gen5", "name": "GP_Gen5_2", "tier": "GeneralPurpose"}, + "tags": {"ElasticServer": "1"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerCreateGeoRestoreMode.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_or_update_a_virtual_network_rule.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_or_update_a_virtual_network_rule.py new file mode 100644 index 000000000000..261d6d546ebd --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/create_or_update_a_virtual_network_rule.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python create_or_update_a_virtual_network_rule.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.virtual_network_rules.begin_create_or_update( + resource_group_name="TestGroup", + server_name="vnet-test-svr", + virtual_network_rule_name="vnet-firewall-rule", + parameters={ + "properties": { + "ignoreMissingVnetServiceEndpoint": False, + "virtualNetworkSubnetId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/TestGroup/providers/Microsoft.Network/virtualNetworks/testvnet/subnets/testsubnet", + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/VirtualNetworkRulesCreateOrUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/creates_or_updates_a_postgre_sql_server_key.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/creates_or_updates_a_postgre_sql_server_key.py new file mode 100644 index 000000000000..8fc7075b077e --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/creates_or_updates_a_postgre_sql_server_key.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python creates_or_updates_a_postgre_sql_server_key.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_keys.begin_create_or_update( + server_name="testserver", + key_name="someVault_someKey_01234567890123456789012345678901", + resource_group_name="testrg", + parameters={ + "properties": { + "serverKeyType": "AzureKeyVault", + "uri": "https://someVault.vault.azure.net/keys/someKey/01234567890123456789012345678901", + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2020-01-01/examples/ServerKeyCreateOrUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_create.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_create.py new file mode 100644 index 000000000000..770ec8060aed --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_create.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python database_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.begin_create_or_update( + resource_group_name="TestGroup", + server_name="testserver", + database_name="db1", + parameters={"properties": {"charset": "UTF8", "collation": "English_United States.1252"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/DatabaseCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_delete.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_delete.py new file mode 100644 index 000000000000..110bdb9953e7 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python database_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.begin_delete( + resource_group_name="TestGroup", + server_name="testserver", + database_name="db1", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/DatabaseDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_get.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_get.py new file mode 100644 index 000000000000..d054c6b475d3 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_get.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python database_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.get( + resource_group_name="TestGroup", + server_name="testserver", + database_name="db1", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/DatabaseGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_list.py new file mode 100644 index 000000000000..300a13ed0b18 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/database_list.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python database_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.list_by_server( + resource_group_name="TestGroup", + server_name="testserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/DatabaseListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_a_database.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_a_database.py new file mode 100644 index 000000000000..7be93081de75 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_a_database.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python delete_a_database.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.begin_delete( + resource_group_name="TestGroup", + server_name="testserver", + database_name="db1", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/DatabaseDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_a_virtual_network_rule.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_a_virtual_network_rule.py new file mode 100644 index 000000000000..6bd31b47e645 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_a_virtual_network_rule.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python delete_a_virtual_network_rule.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.virtual_network_rules.begin_delete( + resource_group_name="TestGroup", + server_name="vnet-test-svr", + virtual_network_rule_name="vnet-firewall-rule", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/VirtualNetworkRulesDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_the_postgre_sql_server_key.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_the_postgre_sql_server_key.py new file mode 100644 index 000000000000..d6928085365e --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/delete_the_postgre_sql_server_key.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python delete_the_postgre_sql_server_key.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_keys.begin_delete( + server_name="testserver", + key_name="someVault_someKey_01234567890123456789012345678901", + resource_group_name="testrg", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2020-01-01/examples/ServerKeyDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/deletes_a_private_endpoint_connection_with_a_given_name..py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/deletes_a_private_endpoint_connection_with_a_given_name..py new file mode 100644 index 000000000000..1616458ebaba --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/deletes_a_private_endpoint_connection_with_a_given_name..py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python deletes_a_private_endpoint_connection_with_a_given_name..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.private_endpoint_connections.begin_delete( + resource_group_name="Default", + server_name="test-svr", + private_endpoint_connection_name="private-endpoint-connection-name", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_create.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_create.py new file mode 100644 index 000000000000..74fae897a3b9 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_create.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python firewall_rule_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.firewall_rules.begin_create_or_update( + resource_group_name="TestGroup", + server_name="testserver", + firewall_rule_name="rule1", + parameters={"properties": {"endIpAddress": "255.255.255.255", "startIpAddress": "0.0.0.0"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/FirewallRuleCreate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_delete.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_delete.py new file mode 100644 index 000000000000..baab444017db --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_delete.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python firewall_rule_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.firewall_rules.begin_delete( + resource_group_name="TestGroup", + server_name="testserver", + firewall_rule_name="rule1", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/FirewallRuleDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_get.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_get.py new file mode 100644 index 000000000000..15057f6dda11 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_get.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python firewall_rule_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.firewall_rules.get( + resource_group_name="TestGroup", + server_name="testserver", + firewall_rule_name="rule1", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/FirewallRuleGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_list.py new file mode 100644 index 000000000000..adf14db6804e --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/firewall_rule_list.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python firewall_rule_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.firewall_rules.list_by_server( + resource_group_name="TestGroup", + server_name="testserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/FirewallRuleListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_backup_for_a_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_backup_for_a_server.py new file mode 100644 index 000000000000..d76da86233a3 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_backup_for_a_server.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python get_a_backup_for_a_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.backups.get( + resource_group_name="TestGroup", + server_name="postgresqltestserver", + backup_name="daily_20210615T160516", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/BackupGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_database.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_database.py new file mode 100644 index 000000000000..e63e172f9510 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_database.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python get_a_database.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.get( + resource_group_name="TestGroup", + server_name="testserver", + database_name="db1", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/DatabaseGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_list_of_server_administrators.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_list_of_server_administrators.py new file mode 100644 index 000000000000..5b323ef5c6e6 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_list_of_server_administrators.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python get_a_list_of_server_administrators.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_administrators.list( + resource_group_name="testrg", + server_name="pgtestsvc4", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerAdminList.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_server's_threat_detection_policy.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_server's_threat_detection_policy.py new file mode 100644 index 000000000000..fe31c2cec72e --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_a_server's_threat_detection_policy.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python get_a_server's_threat_detection_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.server_security_alert_policies.get( + resource_group_name="securityalert-4799", + server_name="securityalert-6440", + security_alert_policy_name="Default", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerSecurityAlertsGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_private_dns_zone_suffix.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_private_dns_zone_suffix.py new file mode 100644 index 000000000000..c042ae84a944 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_private_dns_zone_suffix.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python get_private_dns_zone_suffix.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.get_private_dns_zone_suffix.execute() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/GetPrivateDnsZoneSuffix.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_the_postgre_sql_server_key.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_the_postgre_sql_server_key.py new file mode 100644 index 000000000000..d7fa6c57c2b7 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/get_the_postgre_sql_server_key.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python get_the_postgre_sql_server_key.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_keys.get( + resource_group_name="testrg", + server_name="testserver", + key_name="someVault_someKey_01234567890123456789012345678901", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2020-01-01/examples/ServerKeyGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_a_private_link_resource_for_postgre_sql..py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_a_private_link_resource_for_postgre_sql..py new file mode 100644 index 000000000000..fdc9477b9c52 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_a_private_link_resource_for_postgre_sql..py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python gets_a_private_link_resource_for_postgre_sql..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.private_link_resources.get( + resource_group_name="Default", + server_name="test-svr", + group_name="plr", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateLinkResourcesGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_a_virtual_network_rule.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_a_virtual_network_rule.py new file mode 100644 index 000000000000..1d343c3c9c2d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_a_virtual_network_rule.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python gets_a_virtual_network_rule.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.virtual_network_rules.get( + resource_group_name="TestGroup", + server_name="vnet-test-svr", + virtual_network_rule_name="vnet-firewall-rule", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/VirtualNetworkRulesGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_list_of_private_endpoint_connections_on_a_server..py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_list_of_private_endpoint_connections_on_a_server..py new file mode 100644 index 000000000000..d2e49b6e5758 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_list_of_private_endpoint_connections_on_a_server..py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python gets_list_of_private_endpoint_connections_on_a_server..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.private_endpoint_connections.list_by_server( + resource_group_name="Default", + server_name="test-svr", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionList.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_private_endpoint_connection..py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_private_endpoint_connection..py new file mode 100644 index 000000000000..1a1c9472ad75 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_private_endpoint_connection..py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python gets_private_endpoint_connection..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.private_endpoint_connections.get( + resource_group_name="Default", + server_name="test-svr", + private_endpoint_connection_name="private-endpoint-connection-name", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_private_link_resources_for_postgre_sql..py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_private_link_resources_for_postgre_sql..py new file mode 100644 index 000000000000..126410c893f6 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/gets_private_link_resources_for_postgre_sql..py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python gets_private_link_resources_for_postgre_sql..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.private_link_resources.list_by_server( + resource_group_name="Default", + server_name="test-svr", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateLinkResourcesList.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_backups_for_a_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_backups_for_a_server.py new file mode 100644 index 000000000000..b3255cc56a58 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_backups_for_a_server.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python list_backups_for_a_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.backups.list_by_server( + resource_group_name="TestGroup", + server_name="postgresqltestserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/BackupListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_databases_in_a_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_databases_in_a_server.py new file mode 100644 index 000000000000..2cc5a03779eb --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_databases_in_a_server.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python list_databases_in_a_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.databases.list_by_server( + resource_group_name="TestGroup", + server_name="testserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/DatabasesListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_the_keys_for_a_postgre_sql_server..py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_the_keys_for_a_postgre_sql_server..py new file mode 100644 index 000000000000..153cde2d15fe --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_the_keys_for_a_postgre_sql_server..py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python list_the_keys_for_a_postgre_sql_server..py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_keys.list( + resource_group_name="testrg", + server_name="testserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2020-01-01/examples/ServerKeyList.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_the_server's_threat_detection_policies.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_the_server's_threat_detection_policies.py new file mode 100644 index 000000000000..0f6ed64d15d4 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_the_server's_threat_detection_policies.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python list_the_server's_threat_detection_policies.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.server_security_alert_policies.list_by_server( + resource_group_name="securityalert-4799", + server_name="securityalert-6440", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerSecurityAlertsListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_virtual_network_rules.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_virtual_network_rules.py new file mode 100644 index 000000000000..0e7fc8ae1d32 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/list_virtual_network_rules.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python list_virtual_network_rules.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.virtual_network_rules.list_by_server( + resource_group_name="TestGroup", + server_name="vnet-test-svr", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/VirtualNetworkRulesList.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/log_file_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/log_file_list.py new file mode 100644 index 000000000000..243528ae89cd --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/log_file_list.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python log_file_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.log_files.list_by_server( + resource_group_name="TestGroup", + server_name="testserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/LogFileListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/name_availability.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/name_availability.py new file mode 100644 index 000000000000..3df016da8f6b --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/name_availability.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python name_availability.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.check_name_availability.execute( + name_availability_request={"name": "name1", "type": "Microsoft.DBforPostgreSQL"}, + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/CheckNameAvailability.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/operation_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/operation_list.py new file mode 100644 index 000000000000..30fd17d192dd --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/operation_list.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python operation_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.operations.list() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/OperationList.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/performance_tiers_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/performance_tiers_list.py new file mode 100644 index 000000000000..1c466b66e595 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/performance_tiers_list.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python performance_tiers_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_based_performance_tier.list( + resource_group_name="TestGroup", + server_name="testserver", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/PerformanceTiersListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/replicas_list_by_server.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/replicas_list_by_server.py new file mode 100644 index 000000000000..d6b340648809 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/replicas_list_by_server.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python replicas_list_by_server.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.replicas.list_by_server( + resource_group_name="TestGroup_WestCentralUS", + server_name="testserver-master", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ReplicasListByServer.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrator_create.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrator_create.py new file mode 100644 index 000000000000..49c2d9ceb761 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrator_create.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_administrator_create.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_administrators.begin_create_or_update( + resource_group_name="testrg", + server_name="pgtestsvc4", + properties={ + "properties": { + "administratorType": "ActiveDirectory", + "login": "bob@contoso.com", + "sid": "c6b82b90-a647-49cb-8a62-0d2d3cb7ac7c", + "tenantId": "c6b82b90-a647-49cb-8a62-0d2d3cb7ac7c", + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerAdminCreateUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrator_get.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrator_get.py new file mode 100644 index 000000000000..165d24c51eed --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrator_get.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_administrator_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_administrators.get( + resource_group_name="testrg", + server_name="pgtestsvc4", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerAdminGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrators_delete.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrators_delete.py new file mode 100644 index 000000000000..82706f49a7fe --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_administrators_delete.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_administrators_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.server_administrators.begin_delete( + resource_group_name="testrg", + server_name="pgtestsvc4", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerAdminDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_create_replica.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_create_replica.py new file mode 100644 index 000000000000..88664ba42ce1 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_create_replica.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_create_replica.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="testrg", + server_name="pgtestsvc5rep", + parameters={ + "location": "westus", + "properties": { + "createMode": "Replica", + "pointInTimeUTC": "2021-06-27T00:04:59.4078005+00:00", + "sourceServerResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testrg/providers/Microsoft.DBforPostgreSQL/flexibleServers/sourcepgservername", + }, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerCreateReplica.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_create_with_data_encryption_enabled.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_create_with_data_encryption_enabled.py new file mode 100644 index 000000000000..430702b93fc4 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_create_with_data_encryption_enabled.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_create_with_data_encryption_enabled.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_create( + resource_group_name="testrg", + server_name="pgtestsvc4", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testresourcegroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-usermanagedidentity": {} + }, + }, + "location": "westus", + "properties": { + "administratorLogin": "cloudsa", + "administratorLoginPassword": "password", + "availabilityZone": "1", + "backup": {"backupRetentionDays": 7, "geoRedundantBackup": "Disabled"}, + "createMode": "Create", + "dataEncryption": { + "primaryKeyURI": "https://test-kv.vault.azure.net/keys/test-key1/77f57315bab34b0189daa113fbc78787", + "primaryUserAssignedIdentityId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testresourcegroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-usermanagedidentity", + "type": "AzureKeyVault", + }, + "highAvailability": {"mode": "ZoneRedundant"}, + "network": { + "delegatedSubnetResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/test-vnet-subnet", + "privateDnsZoneArmResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/testrg/providers/Microsoft.Network/privateDnsZones/test-private-dns-zone.postgres.database.azure.com", + }, + "storage": {"storageSizeGB": 512}, + "version": "12", + }, + "sku": {"name": "Standard_D4s_v3", "tier": "GeneralPurpose"}, + "tags": {"ElasticServer": "1"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerCreateWithDataEncryptionEnabled.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_delete.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_delete.py new file mode 100644 index 000000000000..ff8135cd93c3 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_delete.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_delete( + resource_group_name="TestGroup", + server_name="testserver", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_get.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_get.py new file mode 100644 index 000000000000..497f58b435fe --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_get.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_get.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.get( + resource_group_name="testrg", + server_name="pgtestsvc1", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerGet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_get_with_vnet.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_get_with_vnet.py new file mode 100644 index 000000000000..71c659fe7723 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_get_with_vnet.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_get_with_vnet.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.get( + resource_group_name="testrg", + server_name="pgtestsvc4", + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerGetWithVnet.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_list.py new file mode 100644 index 000000000000..c720e67e1c27 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_list.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerList.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_list_by_resource_group.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_list_by_resource_group.py new file mode 100644 index 000000000000..f3bb05884d32 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_list_by_resource_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_list_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.list_by_resource_group( + resource_group_name="TestGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerListByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_restart.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_restart.py new file mode 100644 index 000000000000..77458b850326 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_restart.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_restart.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_restart( + resource_group_name="TestGroup", + server_name="testserver", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerRestart.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_restart_with_failover.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_restart_with_failover.py new file mode 100644 index 000000000000..cf89970c8d40 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_restart_with_failover.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_restart_with_failover.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_restart( + resource_group_name="testrg", + server_name="testserver", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerRestartWithFailover.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_start.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_start.py new file mode 100644 index 000000000000..dd544781d2c1 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_start.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_start.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_start( + resource_group_name="testrg", + server_name="testserver", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerStart.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_stop.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_stop.py new file mode 100644 index 000000000000..3dda8e5acf1d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_stop.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_stop.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_stop( + resource_group_name="testrg", + server_name="testserver", + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerStop.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update.py new file mode 100644 index 000000000000..e2b1ae13a6e2 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_update.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_update( + resource_group_name="testrg", + server_name="pgtestsvc4", + parameters={ + "properties": { + "administratorLoginPassword": "", + "minimalTlsVersion": "TLS1_2", + "sslEnforcement": "Enabled", + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_aad_auth_enabled.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_aad_auth_enabled.py new file mode 100644 index 000000000000..6f162bf4dca9 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_aad_auth_enabled.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_update_with_aad_auth_enabled.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_update( + resource_group_name="TestGroup", + server_name="pgtestsvc4", + parameters={ + "properties": { + "administratorLoginPassword": "newpassword", + "authConfig": {"activeDirectoryAuthEnabled": True, "tenantId": "tttttt-tttt-tttt-tttt-tttttttttttt"}, + "backup": {"backupRetentionDays": 20}, + "createMode": "Update", + "storage": {"storageSizeGB": 1024}, + }, + "sku": {"name": "Standard_D8s_v3", "tier": "GeneralPurpose"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerUpdateWithAadAuthEnabled.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_customer_maintenance_window.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_customer_maintenance_window.py new file mode 100644 index 000000000000..3bb57191dea9 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_customer_maintenance_window.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_update_with_customer_maintenance_window.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_update( + resource_group_name="testrg", + server_name="pgtestsvc4", + parameters={ + "properties": { + "createMode": "Update", + "maintenanceWindow": {"customWindow": "Enabled", "dayOfWeek": 0, "startHour": 8, "startMinute": 0}, + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerUpdateWithCustomerMaintenanceWindow.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_data_encryption_enabled.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_data_encryption_enabled.py new file mode 100644 index 000000000000..268603eb021b --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_data_encryption_enabled.py @@ -0,0 +1,61 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_update_with_data_encryption_enabled.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_update( + resource_group_name="TestGroup", + server_name="pgtestsvc4", + parameters={ + "identity": { + "type": "UserAssigned", + "userAssignedIdentities": { + "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testresourcegroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-usermanagedidentity": {} + }, + }, + "properties": { + "administratorLoginPassword": "newpassword", + "backup": {"backupRetentionDays": 20}, + "createMode": "Update", + "dataEncryption": { + "primaryKeyURI": "https://test-kv.vault.azure.net/keys/test-key1/77f57315bab34b0189daa113fbc78787", + "primaryUserAssignedIdentityId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testresourcegroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-usermanagedidentity", + "type": "AzureKeyVault", + }, + "storage": {"storageSizeGB": 1024}, + }, + "sku": {"name": "Standard_D8s_v3", "tier": "GeneralPurpose"}, + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerUpdateWithDataEncryptionEnabled.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_major_version_upgrade.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_major_version_upgrade.py new file mode 100644 index 000000000000..b0332ebe0326 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/server_update_with_major_version_upgrade.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python server_update_with_major_version_upgrade.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.servers.begin_update( + resource_group_name="testrg", + server_name="pgtestsvc4", + parameters={"properties": {"createMode": "Update", "version": "14"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ServerUpdateWithMajorVersionUpgrade.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_server's_threat_detection_policy_with_all_parameters.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_server's_threat_detection_policy_with_all_parameters.py new file mode 100644 index 000000000000..7b51ce0dbc20 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_server's_threat_detection_policy_with_all_parameters.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python update_a_server's_threat_detection_policy_with_all_parameters.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.server_security_alert_policies.begin_create_or_update( + resource_group_name="securityalert-4799", + server_name="securityalert-6440", + security_alert_policy_name="Default", + parameters={ + "properties": { + "disabledAlerts": ["Access_Anomaly", "Usage_Anomaly"], + "emailAccountAdmins": True, + "emailAddresses": ["testSecurityAlert@microsoft.com"], + "retentionDays": 5, + "state": "Enabled", + "storageAccountAccessKey": "sdlfkjabc+sdlfkjsdlkfsjdfLDKFTERLKFDFKLjsdfksjdflsdkfD2342309432849328476458/3RSD==", + "storageEndpoint": "https://mystorage.blob.core.windows.net", + } + }, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerSecurityAlertsCreateMax.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_server's_threat_detection_policy_with_minimal_parameters.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_server's_threat_detection_policy_with_minimal_parameters.py new file mode 100644 index 000000000000..f617880078d7 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_server's_threat_detection_policy_with_minimal_parameters.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python update_a_server's_threat_detection_policy_with_minimal_parameters.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.server_security_alert_policies.begin_create_or_update( + resource_group_name="securityalert-4799", + server_name="securityalert-6440", + security_alert_policy_name="Default", + parameters={"properties": {"emailAccountAdmins": True, "state": "Disabled"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2017-12-01/examples/ServerSecurityAlertsCreateMin.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_user_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_user_configuration.py new file mode 100644 index 000000000000..c0dc38cf14d4 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_a_user_configuration.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python update_a_user_configuration.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.configurations.begin_update( + resource_group_name="testrg", + server_name="testserver", + configuration_name="event_scheduler", + parameters={"properties": {"source": "user-override", "value": "on"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/ConfigurationUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_private_endpoint_connection_tags.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_private_endpoint_connection_tags.py new file mode 100644 index 000000000000..f281676dc9c2 --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/update_private_endpoint_connection_tags.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python update_private_endpoint_connection_tags.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-1111-2222-3333-444444444444", + ) + + response = client.private_endpoint_connections.begin_update_tags( + resource_group_name="Default", + server_name="test-svr", + private_endpoint_connection_name="private-endpoint-connection-name", + parameters={"tags": {"key1": "val1", "key2": "val2", "key3": "val3"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/stable/2018-06-01/examples/PrivateEndpointConnectionUpdateTags.json +if __name__ == "__main__": + main() diff --git a/sdk/rdbms/azure-mgmt-rdbms/generated_samples/virtual_network_subnet_usage_list.py b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/virtual_network_subnet_usage_list.py new file mode 100644 index 000000000000..88ea964cdb3d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/generated_samples/virtual_network_subnet_usage_list.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.rdbms import PostgreSQLManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-rdbms +# USAGE + python virtual_network_subnet_usage_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = PostgreSQLManagementClient( + credential=DefaultAzureCredential(), + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.virtual_network_subnet_usage.execute( + location_name="westus", + parameters={ + "virtualNetworkArmResourceId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/testvnet" + }, + ) + print(response) + + +# x-ms-original-file: specification/postgresql/resource-manager/Microsoft.DBforPostgreSQL/preview/2022-03-08-preview/examples/VirtualNetworkSubnetUsage.json +if __name__ == "__main__": + main()