diff --git a/sdk/signalr/azure-mgmt-signalr/_meta.json b/sdk/signalr/azure-mgmt-signalr/_meta.json index faaad9c178d7..abfe05d2f4c0 100644 --- a/sdk/signalr/azure-mgmt-signalr/_meta.json +++ b/sdk/signalr/azure-mgmt-signalr/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "commit": "9366804c62e024801daf8a578924099ff644ccf6", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.12.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.1.11", + "@autorest/modelerfour@4.24.3" ], - "commit": "4acb59eaeaeff82d37f7e885096d3668588b33a1", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/signalr/resource-manager/readme.md --multiapi --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --use=@autorest/python@5.12.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/signalr/resource-manager/readme.md --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.1.11 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/signalr/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/__init__.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/__init__.py index a4c83e80f925..de6d7ffe4dc2 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/__init__.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/__init__.py @@ -10,9 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['SignalRManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["SignalRManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_configuration.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_configuration.py index 6b932f223f4f..aeba8559ad5b 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_configuration.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_configuration.py @@ -19,25 +19,26 @@ from azure.core.credentials import TokenCredential -class SignalRManagementClientConfiguration(Configuration): +class SignalRManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for SignalRManagementClient. 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: Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: Gets subscription Id which uniquely identify the Microsoft Azure + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-08-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(SignalRManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-08-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,24 +46,25 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2022-02-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-signalr/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-signalr/{}".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/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_metadata.json b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_metadata.json deleted file mode 100644 index 662aebf16427..000000000000 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_metadata.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - "chosen_version": "2022-02-01", - "total_api_version_list": ["2022-02-01"], - "client": { - "name": "SignalRManagementClient", - "filename": "_signal_rmanagement_client", - "description": "REST API for Azure SignalR Service.", - "host_value": "\"https://management.azure.com\"", - "parameterized_host_template": null, - "azure_arm": true, - "has_lro_operations": true, - "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"SignalRManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"SignalRManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", - "docstring_type": "str", - "required": true - } - }, - "async": { - "credential": { - "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id: str,", - "description": "Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", - "docstring_type": "str", - "required": true - } - }, - "constant": { - }, - "call": "credential, subscription_id", - "service_client_specific": { - "sync": { - "api_version": { - "signature": "api_version=None, # type: Optional[str]", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: str = \"https://management.azure.com\",", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "operations": "Operations", - "signal_r": "SignalROperations", - "usages": "UsagesOperations", - "signal_rcustom_certificates": "SignalRCustomCertificatesOperations", - "signal_rcustom_domains": "SignalRCustomDomainsOperations", - "signal_rprivate_endpoint_connections": "SignalRPrivateEndpointConnectionsOperations", - "signal_rprivate_link_resources": "SignalRPrivateLinkResourcesOperations", - "signal_rshared_private_link_resources": "SignalRSharedPrivateLinkResourcesOperations" - } -} \ No newline at end of file diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_patch.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_patch.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_serialization.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_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/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_signal_rmanagement_client.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_signal_rmanagement_client.py index 1f22d0a3571f..ea14a0a3d181 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_signal_rmanagement_client.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_signal_rmanagement_client.py @@ -7,21 +7,31 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer from . import models from ._configuration import SignalRManagementClientConfiguration -from .operations import Operations, SignalRCustomCertificatesOperations, SignalRCustomDomainsOperations, SignalROperations, SignalRPrivateEndpointConnectionsOperations, SignalRPrivateLinkResourcesOperations, SignalRSharedPrivateLinkResourcesOperations, UsagesOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + Operations, + SignalRCustomCertificatesOperations, + SignalRCustomDomainsOperations, + SignalROperations, + SignalRPrivateEndpointConnectionsOperations, + SignalRPrivateLinkResourcesOperations, + SignalRSharedPrivateLinkResourcesOperations, + UsagesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class SignalRManagementClient: + +class SignalRManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """REST API for Azure SignalR Service. :ivar operations: Operations operations @@ -46,13 +56,16 @@ class SignalRManagementClient: operations :vartype signal_rshared_private_link_resources: azure.mgmt.signalr.operations.SignalRSharedPrivateLinkResourcesOperations - :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: Gets subscription Id which uniquely identify the Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :param base_url: Service URL. Default value is 'https://management.azure.com'. + :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2022-08-01-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 Retry-After header is present. """ @@ -64,7 +77,9 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = SignalRManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = SignalRManagementClientConfiguration( + 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)} @@ -74,18 +89,23 @@ def __init__( self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.signal_r = SignalROperations(self._client, self._config, self._serialize, self._deserialize) self.usages = UsagesOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rcustom_certificates = SignalRCustomCertificatesOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rcustom_domains = SignalRCustomDomainsOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rprivate_endpoint_connections = SignalRPrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rprivate_link_resources = SignalRPrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rshared_private_link_resources = SignalRSharedPrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request, # type: HttpRequest - **kwargs: Any - ) -> HttpResponse: + self.signal_rcustom_certificates = SignalRCustomCertificatesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rcustom_domains = SignalRCustomDomainsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rprivate_endpoint_connections = SignalRPrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rprivate_link_resources = SignalRPrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rshared_private_link_resources = SignalRSharedPrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -94,7 +114,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/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_vendor.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_vendor.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_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/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_version.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_version.py index 59deb8c7263b..e5754a47ce68 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_version.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.1.0" +VERSION = "1.0.0b1" diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/__init__.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/__init__.py index 883d13814096..2861b34c376c 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/__init__.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/__init__.py @@ -7,9 +7,15 @@ # -------------------------------------------------------------------------- from ._signal_rmanagement_client import SignalRManagementClient -__all__ = ['SignalRManagementClient'] -# `._patch.py` is used for handwritten extensions to the generated code -# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md -from ._patch import patch_sdk -patch_sdk() +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["SignalRManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_configuration.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_configuration.py index f2807500c91e..2910a5941238 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_configuration.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_configuration.py @@ -19,25 +19,26 @@ from azure.core.credentials_async import AsyncTokenCredential -class SignalRManagementClientConfiguration(Configuration): +class SignalRManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for SignalRManagementClient. 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: Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + :param subscription_id: Gets subscription Id which uniquely identify the Microsoft Azure + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-08-01-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(SignalRManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-08-01-preview") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -45,23 +46,22 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.api_version = "2022-02-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-signalr/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-signalr/{}".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/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_patch.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_patch.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_signal_rmanagement_client.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_signal_rmanagement_client.py index c2ec56721333..25aa0cd6d4d2 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_signal_rmanagement_client.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/_signal_rmanagement_client.py @@ -7,21 +7,31 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING +from typing import Any, Awaitable, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer from .. import models +from .._serialization import Deserializer, Serializer from ._configuration import SignalRManagementClientConfiguration -from .operations import Operations, SignalRCustomCertificatesOperations, SignalRCustomDomainsOperations, SignalROperations, SignalRPrivateEndpointConnectionsOperations, SignalRPrivateLinkResourcesOperations, SignalRSharedPrivateLinkResourcesOperations, UsagesOperations +from .operations import ( + Operations, + SignalRCustomCertificatesOperations, + SignalRCustomDomainsOperations, + SignalROperations, + SignalRPrivateEndpointConnectionsOperations, + SignalRPrivateLinkResourcesOperations, + SignalRSharedPrivateLinkResourcesOperations, + UsagesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class SignalRManagementClient: + +class SignalRManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """REST API for Azure SignalR Service. :ivar operations: Operations operations @@ -47,13 +57,16 @@ class SignalRManagementClient: operations :vartype signal_rshared_private_link_resources: azure.mgmt.signalr.aio.operations.SignalRSharedPrivateLinkResourcesOperations - :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: Gets subscription Id which uniquely identify the Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. + subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :param base_url: Service URL. Default value is 'https://management.azure.com'. + :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2022-08-01-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 Retry-After header is present. """ @@ -65,7 +78,9 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = SignalRManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = SignalRManagementClientConfiguration( + 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)} @@ -75,18 +90,23 @@ def __init__( self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.signal_r = SignalROperations(self._client, self._config, self._serialize, self._deserialize) self.usages = UsagesOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rcustom_certificates = SignalRCustomCertificatesOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rcustom_domains = SignalRCustomDomainsOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rprivate_endpoint_connections = SignalRPrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rprivate_link_resources = SignalRPrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.signal_rshared_private_link_resources = SignalRSharedPrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + self.signal_rcustom_certificates = SignalRCustomCertificatesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rcustom_domains = SignalRCustomDomainsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rprivate_endpoint_connections = SignalRPrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rprivate_link_resources = SignalRPrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.signal_rshared_private_link_resources = SignalRSharedPrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -95,7 +115,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/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/__init__.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/__init__.py index bab1a78daafd..0fe4134b4d88 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/__init__.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/__init__.py @@ -15,13 +15,19 @@ from ._signal_rprivate_link_resources_operations import SignalRPrivateLinkResourcesOperations from ._signal_rshared_private_link_resources_operations import SignalRSharedPrivateLinkResourcesOperations +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__ = [ - 'Operations', - 'SignalROperations', - 'UsagesOperations', - 'SignalRCustomCertificatesOperations', - 'SignalRCustomDomainsOperations', - 'SignalRPrivateEndpointConnectionsOperations', - 'SignalRPrivateLinkResourcesOperations', - 'SignalRSharedPrivateLinkResourcesOperations', + "Operations", + "SignalROperations", + "UsagesOperations", + "SignalRCustomCertificatesOperations", + "SignalRCustomDomainsOperations", + "SignalRPrivateEndpointConnectionsOperations", + "SignalRPrivateLinkResourcesOperations", + "SignalRSharedPrivateLinkResourcesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_operations.py index 7f7358249b77..026c4a3fb8fc 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,80 +6,102 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationList"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available REST API operations of the Microsoft.SignalRService provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.OperationList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -92,7 +115,9 @@ 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(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]: @@ -102,8 +127,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.SignalRService/operations'} # type: ignore + list.metadata = {"url": "/providers/Microsoft.SignalRService/operations"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_patch.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_r_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_r_operations.py index 20c487388ef1..832e0397305d 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_r_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_r_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,88 +6,170 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._signal_r_operations import build_check_name_availability_request, build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_by_subscription_request, build_list_keys_request, build_list_skus_request, build_regenerate_key_request_initial, build_restart_request_initial, build_update_request_initial -T = TypeVar('T') +from ...operations._signal_r_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_by_subscription_request, + build_list_keys_request, + build_list_skus_request, + build_regenerate_key_request, + build_restart_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SignalROperations: - """SignalROperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SignalROperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`signal_r` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async + @overload async def check_name_availability( self, location: str, - parameters: "_models.NameAvailabilityParameters", + parameters: _models.NameAvailabilityParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.NameAvailability": + ) -> _models.NameAvailability: """Checks that the resource name is valid and is not already in use. - :param location: the region. + :param location: the region. Required. :type location: str - :param parameters: Parameters supplied to the operation. + :param parameters: Parameters supplied to the operation. Required. :type parameters: ~azure.mgmt.signalr.models.NameAvailabilityParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default 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.signalr.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, location: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.NameAvailability: + """Checks that the resource name is valid and is not already in use. + + :param location: the region. Required. + :type location: str + :param parameters: Parameters supplied to the 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 - :return: NameAvailability, or the result of cls(response) + :return: NameAvailability or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, parameters: Union[_models.NameAvailabilityParameters, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Checks that the resource name is valid and is not already in use. + + :param location: the region. Required. + :type location: str + :param parameters: Parameters supplied to the operation. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.signalr.models.NameAvailabilityParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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.signalr.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] - _json = self._serialize.body(parameters, 'NameAvailabilityParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "NameAvailabilityParameters") request = build_check_name_availability_request( location=location, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -94,51 +177,66 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/checkNameAvailability'} # type: ignore - + check_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/checkNameAvailability"} # type: ignore @distributed_trace - def list_by_subscription( - self, - **kwargs: Any - ) -> AsyncIterable["_models.SignalRResourceList"]: + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.SignalRResource"]: """Handles requests to list all resources in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SignalRResourceList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SignalRResourceList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SignalRResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -152,7 +250,9 @@ 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(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]: @@ -162,53 +262,67 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/signalR'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/signalR"} # type: ignore @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.SignalRResourceList"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SignalRResource"]: """Handles requests to list all resources in a resource group. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. 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 SignalRResourceList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SignalRResourceList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SignalRResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -222,7 +336,9 @@ 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(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]: @@ -232,48 +348,54 @@ 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.SignalRService/signalR'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SignalRResource": + async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.SignalRResource: """Get the resource and its properties. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SignalRResource, or the result of cls(response) + :return: SignalRResource or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SignalRResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResource] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -281,83 +403,178 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> Optional["_models.SignalRResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.SignalRResource"]] + ) -> Optional[_models.SignalRResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'SignalRResource') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.SignalRResource]] - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "SignalRResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(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('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + parameters: _models.SignalRResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SignalRResource]: + """Create or update a resource. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the create or update operation. Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SignalRResource]: + """Create or update a resource. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the create or update 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.SignalRResource"]: + ) -> AsyncLROPoller[_models.SignalRResource]: """Create or update a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: Parameters for the create or update operation. - :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :param parameters: Parameters for the create or update operation. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -369,98 +586,107 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either SignalRResource or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResource] + 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( + raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore @distributed_trace_async - async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_delete(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Operation to delete a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -472,108 +698,211 @@ async def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore async def _update_initial( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> Optional["_models.SignalRResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.SignalRResource"]] + ) -> Optional[_models.SignalRResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'SignalRResource') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.SignalRResource]] - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "SignalRResource") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(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 if response.status_code == 200: - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + parameters: _models.SignalRResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SignalRResource]: + """Operation to update an exiting resource. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the update operation. Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SignalRResource]: + """Operation to update an exiting resource. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the update 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_update( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.SignalRResource"]: + ) -> AsyncLROPoller[_models.SignalRResource]: """Operation to update an exiting resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: Parameters for the update operation. - :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :param parameters: Parameters for the update operation. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -585,86 +914,98 @@ async def begin_update( :return: An instance of AsyncLROPoller that returns either SignalRResource or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResource] + 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( + raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore @distributed_trace_async - async def list_keys( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SignalRKeys": + async def list_keys(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.SignalRKeys: """Get the access keys of the resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SignalRKeys, or the result of cls(response) + :return: SignalRKeys or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SignalRKeys - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRKeys"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRKeys] - request = build_list_keys_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list_keys.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_keys.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -672,79 +1013,176 @@ async def list_keys( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SignalRKeys', pipeline_response) + deserialized = self._deserialize("SignalRKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/listKeys'} # type: ignore - + list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/listKeys"} # type: ignore async def _regenerate_key_initial( self, resource_group_name: str, resource_name: str, - parameters: "_models.RegenerateKeyParameters", + parameters: Union[_models.RegenerateKeyParameters, IO], **kwargs: Any - ) -> "_models.SignalRKeys": - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRKeys"] + ) -> _models.SignalRKeys: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'RegenerateKeyParameters') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRKeys] - request = build_regenerate_key_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RegenerateKeyParameters") + + request = build_regenerate_key_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._regenerate_key_initial.metadata['url'], + content=_content, + template_url=self._regenerate_key_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [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 = self._deserialize('SignalRKeys', pipeline_response) + deserialized = self._deserialize("SignalRKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _regenerate_key_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey'} # type: ignore + _regenerate_key_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey"} # type: ignore + @overload + async def begin_regenerate_key( + self, + resource_group_name: str, + resource_name: str, + parameters: _models.RegenerateKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SignalRKeys]: + """Regenerate the access key for the resource. PrimaryKey and SecondaryKey cannot be regenerated + at the same time. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameter that describes the Regenerate Key Operation. Required. + :type parameters: ~azure.mgmt.signalr.models.RegenerateKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 SignalRKeys or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRKeys] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_regenerate_key( + self, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SignalRKeys]: + """Regenerate the access key for the resource. PrimaryKey and SecondaryKey cannot be regenerated + at the same time. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameter that describes the Regenerate Key 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 SignalRKeys or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRKeys] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_regenerate_key( self, resource_group_name: str, resource_name: str, - parameters: "_models.RegenerateKeyParameters", + parameters: Union[_models.RegenerateKeyParameters, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.SignalRKeys"]: + ) -> AsyncLROPoller[_models.SignalRKeys]: """Regenerate the access key for the resource. PrimaryKey and SecondaryKey cannot be regenerated at the same time. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: Parameter that describes the Regenerate Key Operation. - :type parameters: ~azure.mgmt.signalr.models.RegenerateKeyParameters + :param parameters: Parameter that describes the Regenerate Key Operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.RegenerateKeyParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -756,98 +1194,110 @@ async def begin_regenerate_key( :return: An instance of AsyncLROPoller that returns either SignalRKeys or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SignalRKeys] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRKeys"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRKeys] + 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._regenerate_key_initial( + raw_result = await self._regenerate_key_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SignalRKeys', pipeline_response) + deserialized = self._deserialize("SignalRKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_regenerate_key.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey'} # type: ignore + begin_regenerate_key.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey"} # type: ignore - async def _restart_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any + async def _restart_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_restart_request( resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._restart_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._restart_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [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, {}) - _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart'} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart"} # type: ignore @distributed_trace_async - async def begin_restart( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_restart(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Operation to restart a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -859,80 +1309,96 @@ async def begin_restart( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._restart_initial( + raw_result = await self._restart_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart'} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart"} # type: ignore @distributed_trace_async - async def list_skus( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SkuList": + async def list_skus(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.SkuList: """List all available skus of the resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SkuList, or the result of cls(response) + :return: SkuList or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SkuList - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SkuList"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SkuList] - request = build_list_skus_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list_skus.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_skus.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -940,12 +1406,11 @@ async def list_skus( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SkuList', pipeline_response) + deserialized = self._deserialize("SkuList", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_skus.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/skus'} # type: ignore - + list_skus.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/skus"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_certificates_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_certificates_operations.py index b2d6ea78cac1..05f80f758224 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_certificates_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_certificates_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,97 +6,120 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._signal_rcustom_certificates_operations import build_create_or_update_request_initial, build_delete_request, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._signal_rcustom_certificates_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SignalRCustomCertificatesOperations: - """SignalRCustomCertificatesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SignalRCustomCertificatesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`signal_rcustom_certificates` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.CustomCertificateList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.CustomCertificate"]: """List all custom certificates. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomCertificateList or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.CustomCertificateList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CustomCertificate or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.CustomCertificate] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificateList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificateList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -109,7 +133,9 @@ 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(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]: @@ -119,52 +145,59 @@ 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.SignalRService/signalR/{resourceName}/customCertificates'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - certificate_name: str, - **kwargs: Any - ) -> "_models.CustomCertificate": + self, resource_group_name: str, resource_name: str, certificate_name: str, **kwargs: Any + ) -> _models.CustomCertificate: """Get a custom certificate. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param certificate_name: Custom certificate name. + :param certificate_name: Custom certificate name. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomCertificate, or the result of cls(response) + :return: CustomCertificate or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.CustomCertificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificate] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -172,66 +205,163 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, certificate_name: str, - parameters: "_models.CustomCertificate", + parameters: Union[_models.CustomCertificate, IO], **kwargs: Any - ) -> "_models.CustomCertificate": - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificate"] + ) -> _models.CustomCertificate: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CustomCertificate') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificate] - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CustomCertificate") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + certificate_name: str, + parameters: _models.CustomCertificate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CustomCertificate]: + """Create or update a custom certificate. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param certificate_name: Custom certificate name. Required. + :type certificate_name: str + :param parameters: Required. + :type parameters: ~azure.mgmt.signalr.models.CustomCertificate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 CustomCertificate or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.CustomCertificate] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + certificate_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CustomCertificate]: + """Create or update a custom certificate. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param certificate_name: Custom certificate name. Required. + :type certificate_name: str + :param parameters: Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 CustomCertificate or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.CustomCertificate] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -239,20 +369,23 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, certificate_name: str, - parameters: "_models.CustomCertificate", + parameters: Union[_models.CustomCertificate, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.CustomCertificate"]: + ) -> AsyncLROPoller[_models.CustomCertificate]: """Create or update a custom certificate. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param certificate_name: Custom certificate name. + :param certificate_name: Custom certificate name. Required. :type certificate_name: str - :param parameters: - :type parameters: ~azure.mgmt.signalr.models.CustomCertificate + :param parameters: Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.CustomCertificate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/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 @@ -264,91 +397,104 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either CustomCertificate or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.CustomCertificate] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificate"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificate] + 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( + raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore @distributed_trace_async - async def delete( - self, - resource_group_name: str, - resource_name: str, - certificate_name: str, - **kwargs: Any + async def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, certificate_name: str, **kwargs: Any ) -> None: """Delete a custom certificate. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param certificate_name: Custom certificate name. + :param certificate_name: Custom certificate name. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_delete_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, - template_url=self.delete.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -359,5 +505,4 @@ async def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_domains_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_domains_operations.py index 4782d77bbae2..a829bd84af4b 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_domains_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rcustom_domains_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,120 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._signal_rcustom_domains_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._signal_rcustom_domains_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SignalRCustomDomainsOperations: - """SignalRCustomDomainsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SignalRCustomDomainsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`signal_rcustom_domains` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.CustomDomainList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.CustomDomain"]: """List all custom domains. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomDomainList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.CustomDomainList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CustomDomain or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.CustomDomain] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomainList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomainList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -107,7 +133,9 @@ 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(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]: @@ -117,52 +145,57 @@ 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.SignalRService/signalR/{resourceName}/customDomains'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - resource_name: str, - name: str, - **kwargs: Any - ) -> "_models.CustomDomain": + async def get(self, resource_group_name: str, resource_name: str, name: str, **kwargs: Any) -> _models.CustomDomain: """Get a custom domain. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param name: Custom domain name. + :param name: Custom domain name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomDomain, or the result of cls(response) + :return: CustomDomain or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.CustomDomain - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomain"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, name=name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -170,62 +203,159 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomDomain', pipeline_response) + deserialized = self._deserialize("CustomDomain", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, name: str, - parameters: "_models.CustomDomain", + parameters: Union[_models.CustomDomain, IO], **kwargs: Any - ) -> "_models.CustomDomain": - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomain"] + ) -> _models.CustomDomain: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CustomDomain') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain] - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CustomDomain") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, name=name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomDomain', pipeline_response) + deserialized = self._deserialize("CustomDomain", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + name: str, + parameters: _models.CustomDomain, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CustomDomain]: + """Create or update a custom domain. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param name: Custom domain name. Required. + :type name: str + :param parameters: Required. + :type parameters: ~azure.mgmt.signalr.models.CustomDomain + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 CustomDomain or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.CustomDomain] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CustomDomain]: + """Create or update a custom domain. + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param name: Custom domain name. Required. + :type name: str + :param parameters: Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 CustomDomain or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.CustomDomain] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -233,20 +363,23 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, name: str, - parameters: "_models.CustomDomain", + parameters: Union[_models.CustomDomain, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.CustomDomain"]: + ) -> AsyncLROPoller[_models.CustomDomain]: """Create or update a custom domain. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param name: Custom domain name. + :param name: Custom domain name. Required. :type name: str - :param parameters: - :type parameters: ~azure.mgmt.signalr.models.CustomDomain + :param parameters: Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.CustomDomain or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/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 @@ -258,104 +391,113 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either CustomDomain or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.CustomDomain] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomain"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain] + 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( + raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, name=name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('CustomDomain', pipeline_response) + deserialized = self._deserialize("CustomDomain", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore - async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, name=name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - name: str, - **kwargs: Any + self, resource_group_name: str, resource_name: str, name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Delete a custom domain. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param name: Custom domain name. + :param name: Custom domain name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -367,41 +509,48 @@ async def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, name=name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_endpoint_connections_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_endpoint_connections_operations.py index 4fd05a5a8d75..eb0cdbcf26d2 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_endpoint_connections_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_endpoint_connections_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,97 +6,122 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._signal_rprivate_endpoint_connections_operations import build_delete_request_initial, build_get_request, build_list_request, build_update_request -T = TypeVar('T') +from ...operations._signal_rprivate_endpoint_connections_operations import ( + build_delete_request, + build_get_request, + build_list_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SignalRPrivateEndpointConnectionsOperations: - """SignalRPrivateEndpointConnectionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SignalRPrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`signal_rprivate_endpoint_connections` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.PrivateEndpointConnectionList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateEndpointConnection"]: """List private endpoint connections. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateEndpointConnectionList or the result of + :return: An iterator like instance of either PrivateEndpointConnection or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.PrivateEndpointConnectionList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnectionList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -109,7 +135,9 @@ 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(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]: @@ -119,52 +147,59 @@ 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.SignalRService/signalR/{resourceName}/privateEndpointConnections'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections"} # type: ignore @distributed_trace_async async def get( - self, - private_endpoint_connection_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get the specified private endpoint connection. - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - request = build_get_request( private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -172,15 +207,76 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + + @overload + async def update( + self, + private_endpoint_connection_name: str, + resource_group_name: str, + resource_name: str, + parameters: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Update the state of specified private endpoint connection. + + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The resource of private endpoint and its properties. Required. + :type parameters: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + private_endpoint_connection_name: str, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Update the state of specified private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The resource of private endpoint and its properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def update( @@ -188,48 +284,72 @@ async def update( private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, - parameters: "_models.PrivateEndpointConnection", + parameters: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + ) -> _models.PrivateEndpointConnection: """Update the state of specified private endpoint connection. - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: The resource of private endpoint and its properties. - :type parameters: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :param parameters: The resource of private endpoint and its properties. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.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_update_request( private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -237,69 +357,73 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - async def _delete_initial( - self, - private_endpoint_connection_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace_async async def begin_delete( - self, - private_endpoint_connection_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + self, private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Delete the specified private endpoint connection. - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -311,41 +435,48 @@ async def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore private_endpoint_connection_name=private_endpoint_connection_name, resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_link_resources_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_link_resources_operations.py index ff7533bab4a3..6db1847d9ea0 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_link_resources_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rprivate_link_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,112 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace -from azure.core.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._signal_rprivate_link_resources_operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SignalRPrivateLinkResourcesOperations: - """SignalRPrivateLinkResourcesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SignalRPrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`signal_rprivate_link_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.PrivateLinkResourceList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateLinkResource"]: """Get the private link resources that need to be created for a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateLinkResourceList or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.PrivateLinkResourceList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -107,7 +125,9 @@ 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(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]: @@ -117,8 +137,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateLinkResources'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateLinkResources"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rshared_private_link_resources_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rshared_private_link_resources_operations.py index 07cbd131abf0..2e3abb270b78 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rshared_private_link_resources_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_signal_rshared_private_link_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,97 +6,122 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._signal_rshared_private_link_resources_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._signal_rshared_private_link_resources_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class SignalRSharedPrivateLinkResourcesOperations: - """SignalRSharedPrivateLinkResourcesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class SignalRSharedPrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`signal_rshared_private_link_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.SharedPrivateLinkResourceList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.SharedPrivateLinkResource"]: """List shared private link resources. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SharedPrivateLinkResourceList or the result of + :return: An iterator like instance of either SharedPrivateLinkResource or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SharedPrivateLinkResourceList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SharedPrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -109,7 +135,9 @@ 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(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]: @@ -119,52 +147,60 @@ 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.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources"} # type: ignore @distributed_trace_async async def get( - self, - shared_private_link_resource_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SharedPrivateLinkResource": + self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.SharedPrivateLinkResource: """Get the specified shared private link resource. :param shared_private_link_resource_name: The name of the shared private link resource. + Required. :type shared_private_link_resource_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SharedPrivateLinkResource, or the result of cls(response) + :return: SharedPrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SharedPrivateLinkResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResource] - request = build_get_request( shared_private_link_resource_name=shared_private_link_resource_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -172,66 +208,167 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore async def _create_or_update_initial( self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, - parameters: "_models.SharedPrivateLinkResource", + parameters: Union[_models.SharedPrivateLinkResource, IO], **kwargs: Any - ) -> "_models.SharedPrivateLinkResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResource"] + ) -> _models.SharedPrivateLinkResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResource] - _json = self._serialize.body(parameters, 'SharedPrivateLinkResource') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "SharedPrivateLinkResource") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( shared_private_link_resource_name=shared_private_link_resource_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore + + @overload + async def begin_create_or_update( + self, + shared_private_link_resource_name: str, + resource_group_name: str, + resource_name: str, + parameters: _models.SharedPrivateLinkResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SharedPrivateLinkResource]: + """Create or update a shared private link resource. + + :param shared_private_link_resource_name: The name of the shared private link resource. + Required. + :type shared_private_link_resource_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The shared private link resource. Required. + :type parameters: ~azure.mgmt.signalr.models.SharedPrivateLinkResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 SharedPrivateLinkResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SharedPrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + shared_private_link_resource_name: str, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.SharedPrivateLinkResource]: + """Create or update a shared private link resource. + :param shared_private_link_resource_name: The name of the shared private link resource. + Required. + :type shared_private_link_resource_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The shared private link resource. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A 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 SharedPrivateLinkResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SharedPrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -239,20 +376,25 @@ async def begin_create_or_update( shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, - parameters: "_models.SharedPrivateLinkResource", + parameters: Union[_models.SharedPrivateLinkResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.SharedPrivateLinkResource"]: + ) -> AsyncLROPoller[_models.SharedPrivateLinkResource]: """Create or update a shared private link resource. :param shared_private_link_resource_name: The name of the shared private link resource. + Required. :type shared_private_link_resource_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: The shared private link resource. - :type parameters: ~azure.mgmt.signalr.models.SharedPrivateLinkResource + :param parameters: The shared private link resource. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.signalr.models.SharedPrivateLinkResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -265,104 +407,114 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.signalr.models.SharedPrivateLinkResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResource] + 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( + raw_result = await self._create_or_update_initial( # type: ignore shared_private_link_resource_name=shared_private_link_resource_name, resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore - async def _delete_initial( - self, - shared_private_link_resource_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - - request = build_delete_request_initial( + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( shared_private_link_resource_name=shared_private_link_resource_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore @distributed_trace_async async def begin_delete( - self, - shared_private_link_resource_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Delete the specified shared private link resource. :param shared_private_link_resource_name: The name of the shared private link resource. + Required. :type shared_private_link_resource_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -374,41 +526,48 @@ async def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore shared_private_link_resource_name=shared_private_link_resource_name, resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_usages_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_usages_operations.py index aa1860efef37..1490d3e4842e 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_usages_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/aio/operations/_usages_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,106 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace -from azure.core.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._usages_operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class UsagesOperations: - """UsagesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class UsagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.aio.SignalRManagementClient`'s + :attr:`usages` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - location: str, - **kwargs: Any - ) -> AsyncIterable["_models.SignalRUsageList"]: + def list(self, location: str, **kwargs: Any) -> AsyncIterable["_models.SignalRUsage"]: """List resource usage quotas by location. - :param location: the location like "eastus". + :param location: the location like "eastus". Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SignalRUsageList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SignalRUsageList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SignalRUsage or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.signalr.models.SignalRUsage] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRUsageList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRUsageList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( location=location, subscription_id=self._config.subscription_id, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - location=location, - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -99,7 +119,9 @@ 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(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]: @@ -109,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}/providers/Microsoft.SignalRService/locations/{location}/usages'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/usages"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/__init__.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/__init__.py index 77981208a65d..e98cc00204a0 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/__init__.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/__init__.py @@ -41,6 +41,7 @@ from ._models_py3 import ResourceLogConfiguration from ._models_py3 import ResourceReference from ._models_py3 import ResourceSku +from ._models_py3 import ServerlessSettings from ._models_py3 import ServerlessUpstreamSettings from ._models_py3 import ServiceSpecification from ._models_py3 import ShareablePrivateLinkResourceProperties @@ -66,94 +67,97 @@ from ._models_py3 import UpstreamTemplate from ._models_py3 import UserAssignedIdentityProperty - -from ._signal_rmanagement_client_enums import ( - ACLAction, - CreatedByType, - FeatureFlags, - KeyType, - ManagedIdentityType, - PrivateLinkServiceConnectionStatus, - ProvisioningState, - ScaleType, - ServiceKind, - SharedPrivateLinkResourceStatus, - SignalRRequestType, - SignalRSkuTier, - UpstreamAuthType, -) +from ._signal_rmanagement_client_enums import ACLAction +from ._signal_rmanagement_client_enums import CreatedByType +from ._signal_rmanagement_client_enums import FeatureFlags +from ._signal_rmanagement_client_enums import KeyType +from ._signal_rmanagement_client_enums import ManagedIdentityType +from ._signal_rmanagement_client_enums import PrivateLinkServiceConnectionStatus +from ._signal_rmanagement_client_enums import ProvisioningState +from ._signal_rmanagement_client_enums import ScaleType +from ._signal_rmanagement_client_enums import ServiceKind +from ._signal_rmanagement_client_enums import SharedPrivateLinkResourceStatus +from ._signal_rmanagement_client_enums import SignalRRequestType +from ._signal_rmanagement_client_enums import SignalRSkuTier +from ._signal_rmanagement_client_enums import UpstreamAuthType +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__ = [ - 'CustomCertificate', - 'CustomCertificateList', - 'CustomDomain', - 'CustomDomainList', - 'Dimension', - 'ErrorAdditionalInfo', - 'ErrorDetail', - 'ErrorResponse', - 'LiveTraceCategory', - 'LiveTraceConfiguration', - 'LogSpecification', - 'ManagedIdentity', - 'ManagedIdentitySettings', - 'MetricSpecification', - 'NameAvailability', - 'NameAvailabilityParameters', - 'NetworkACL', - 'Operation', - 'OperationDisplay', - 'OperationList', - 'OperationProperties', - 'PrivateEndpoint', - 'PrivateEndpointACL', - 'PrivateEndpointConnection', - 'PrivateEndpointConnectionList', - 'PrivateLinkResource', - 'PrivateLinkResourceList', - 'PrivateLinkServiceConnectionState', - 'ProxyResource', - 'RegenerateKeyParameters', - 'Resource', - 'ResourceLogCategory', - 'ResourceLogConfiguration', - 'ResourceReference', - 'ResourceSku', - 'ServerlessUpstreamSettings', - 'ServiceSpecification', - 'ShareablePrivateLinkResourceProperties', - 'ShareablePrivateLinkResourceType', - 'SharedPrivateLinkResource', - 'SharedPrivateLinkResourceList', - 'SignalRCorsSettings', - 'SignalRFeature', - 'SignalRKeys', - 'SignalRNetworkACLs', - 'SignalRResource', - 'SignalRResourceList', - 'SignalRTlsSettings', - 'SignalRUsage', - 'SignalRUsageList', - 'SignalRUsageName', - 'Sku', - 'SkuCapacity', - 'SkuList', - 'SystemData', - 'TrackedResource', - 'UpstreamAuthSettings', - 'UpstreamTemplate', - 'UserAssignedIdentityProperty', - 'ACLAction', - 'CreatedByType', - 'FeatureFlags', - 'KeyType', - 'ManagedIdentityType', - 'PrivateLinkServiceConnectionStatus', - 'ProvisioningState', - 'ScaleType', - 'ServiceKind', - 'SharedPrivateLinkResourceStatus', - 'SignalRRequestType', - 'SignalRSkuTier', - 'UpstreamAuthType', + "CustomCertificate", + "CustomCertificateList", + "CustomDomain", + "CustomDomainList", + "Dimension", + "ErrorAdditionalInfo", + "ErrorDetail", + "ErrorResponse", + "LiveTraceCategory", + "LiveTraceConfiguration", + "LogSpecification", + "ManagedIdentity", + "ManagedIdentitySettings", + "MetricSpecification", + "NameAvailability", + "NameAvailabilityParameters", + "NetworkACL", + "Operation", + "OperationDisplay", + "OperationList", + "OperationProperties", + "PrivateEndpoint", + "PrivateEndpointACL", + "PrivateEndpointConnection", + "PrivateEndpointConnectionList", + "PrivateLinkResource", + "PrivateLinkResourceList", + "PrivateLinkServiceConnectionState", + "ProxyResource", + "RegenerateKeyParameters", + "Resource", + "ResourceLogCategory", + "ResourceLogConfiguration", + "ResourceReference", + "ResourceSku", + "ServerlessSettings", + "ServerlessUpstreamSettings", + "ServiceSpecification", + "ShareablePrivateLinkResourceProperties", + "ShareablePrivateLinkResourceType", + "SharedPrivateLinkResource", + "SharedPrivateLinkResourceList", + "SignalRCorsSettings", + "SignalRFeature", + "SignalRKeys", + "SignalRNetworkACLs", + "SignalRResource", + "SignalRResourceList", + "SignalRTlsSettings", + "SignalRUsage", + "SignalRUsageList", + "SignalRUsageName", + "Sku", + "SkuCapacity", + "SkuList", + "SystemData", + "TrackedResource", + "UpstreamAuthSettings", + "UpstreamTemplate", + "UserAssignedIdentityProperty", + "ACLAction", + "CreatedByType", + "FeatureFlags", + "KeyType", + "ManagedIdentityType", + "PrivateLinkServiceConnectionStatus", + "ProvisioningState", + "ScaleType", + "ServiceKind", + "SharedPrivateLinkResourceStatus", + "SignalRRequestType", + "SignalRSkuTier", + "UpstreamAuthType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_models_py3.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_models_py3.py index 0c4a65d16388..116bb3f497e9 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_models_py3.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/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,15 +8,16 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._signal_rmanagement_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """The core properties of ARM resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -29,24 +31,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 @@ -66,24 +64,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 CustomCertificate(ProxyResource): @@ -101,37 +95,36 @@ class CustomCertificate(ProxyResource): :vartype type: str :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.signalr.models.SystemData - :ivar provisioning_state: Provisioning state of the resource. Possible values include: - "Unknown", "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", - "Moving". + :ivar provisioning_state: Provisioning state of the resource. Known values are: "Unknown", + "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", and "Moving". :vartype provisioning_state: str or ~azure.mgmt.signalr.models.ProvisioningState - :ivar key_vault_base_uri: Required. Base uri of the KeyVault that stores certificate. + :ivar key_vault_base_uri: Base uri of the KeyVault that stores certificate. Required. :vartype key_vault_base_uri: str - :ivar key_vault_secret_name: Required. Certificate secret name. + :ivar key_vault_secret_name: Certificate secret name. Required. :vartype key_vault_secret_name: str :ivar key_vault_secret_version: Certificate secret version. :vartype key_vault_secret_version: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'key_vault_base_uri': {'required': True}, - 'key_vault_secret_name': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "key_vault_base_uri": {"required": True}, + "key_vault_secret_name": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'key_vault_base_uri': {'key': 'properties.keyVaultBaseUri', 'type': 'str'}, - 'key_vault_secret_name': {'key': 'properties.keyVaultSecretName', 'type': 'str'}, - 'key_vault_secret_version': {'key': 'properties.keyVaultSecretVersion', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "key_vault_base_uri": {"key": "properties.keyVaultBaseUri", "type": "str"}, + "key_vault_secret_name": {"key": "properties.keyVaultSecretName", "type": "str"}, + "key_vault_secret_version": {"key": "properties.keyVaultSecretVersion", "type": "str"}, } def __init__( @@ -143,14 +136,14 @@ def __init__( **kwargs ): """ - :keyword key_vault_base_uri: Required. Base uri of the KeyVault that stores certificate. + :keyword key_vault_base_uri: Base uri of the KeyVault that stores certificate. Required. :paramtype key_vault_base_uri: str - :keyword key_vault_secret_name: Required. Certificate secret name. + :keyword key_vault_secret_name: Certificate secret name. Required. :paramtype key_vault_secret_name: str :keyword key_vault_secret_version: Certificate secret version. :paramtype key_vault_secret_version: str """ - super(CustomCertificate, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.provisioning_state = None self.key_vault_base_uri = key_vault_base_uri @@ -158,7 +151,7 @@ def __init__( self.key_vault_secret_version = key_vault_secret_version -class CustomCertificateList(msrest.serialization.Model): +class CustomCertificateList(_serialization.Model): """Custom certificates list. :ivar value: List of custom certificates of this resource. @@ -169,16 +162,12 @@ class CustomCertificateList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[CustomCertificate]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[CustomCertificate]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["CustomCertificate"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.CustomCertificate"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: List of custom certificates of this resource. @@ -188,7 +177,7 @@ def __init__( It's null for now, added for future use. :paramtype next_link: str """ - super(CustomCertificateList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -208,57 +197,50 @@ class CustomDomain(ProxyResource): :vartype type: str :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.signalr.models.SystemData - :ivar provisioning_state: Provisioning state of the resource. Possible values include: - "Unknown", "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", - "Moving". + :ivar provisioning_state: Provisioning state of the resource. Known values are: "Unknown", + "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", and "Moving". :vartype provisioning_state: str or ~azure.mgmt.signalr.models.ProvisioningState - :ivar domain_name: Required. The custom domain name. + :ivar domain_name: The custom domain name. Required. :vartype domain_name: str - :ivar custom_certificate: Required. Reference to a resource. + :ivar custom_certificate: Reference to a resource. Required. :vartype custom_certificate: ~azure.mgmt.signalr.models.ResourceReference """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'domain_name': {'required': True}, - 'custom_certificate': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "domain_name": {"required": True}, + "custom_certificate": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'domain_name': {'key': 'properties.domainName', 'type': 'str'}, - 'custom_certificate': {'key': 'properties.customCertificate', 'type': 'ResourceReference'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "domain_name": {"key": "properties.domainName", "type": "str"}, + "custom_certificate": {"key": "properties.customCertificate", "type": "ResourceReference"}, } - def __init__( - self, - *, - domain_name: str, - custom_certificate: "ResourceReference", - **kwargs - ): + def __init__(self, *, domain_name: str, custom_certificate: "_models.ResourceReference", **kwargs): """ - :keyword domain_name: Required. The custom domain name. + :keyword domain_name: The custom domain name. Required. :paramtype domain_name: str - :keyword custom_certificate: Required. Reference to a resource. + :keyword custom_certificate: Reference to a resource. Required. :paramtype custom_certificate: ~azure.mgmt.signalr.models.ResourceReference """ - super(CustomDomain, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.provisioning_state = None self.domain_name = domain_name self.custom_certificate = custom_certificate -class CustomDomainList(msrest.serialization.Model): +class CustomDomainList(_serialization.Model): """Custom domains list. :ivar value: List of custom domains that bind to this resource. @@ -269,16 +251,12 @@ class CustomDomainList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[CustomDomain]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[CustomDomain]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["CustomDomain"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.CustomDomain"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: List of custom domains that bind to this resource. @@ -288,12 +266,12 @@ def __init__( It's null for now, added for future use. :paramtype next_link: str """ - super(CustomDomainList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class Dimension(msrest.serialization.Model): +class Dimension(_serialization.Model): """Specifications of the Dimension of metrics. :ivar name: The public facing name of the dimension. @@ -308,10 +286,10 @@ class Dimension(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'internal_name': {'key': 'internalName', 'type': 'str'}, - 'to_be_exported_for_shoebox': {'key': 'toBeExportedForShoebox', 'type': 'bool'}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "internal_name": {"key": "internalName", "type": "str"}, + "to_be_exported_for_shoebox": {"key": "toBeExportedForShoebox", "type": "bool"}, } def __init__( @@ -334,14 +312,14 @@ def __init__( included for the shoebox export scenario. :paramtype to_be_exported_for_shoebox: bool """ - super(Dimension, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.display_name = display_name self.internal_name = internal_name self.to_be_exported_for_shoebox = to_be_exported_for_shoebox -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. @@ -349,31 +327,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 ErrorDetail(msrest.serialization.Model): +class ErrorDetail(_serialization.Model): """The error detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -391,28 +365,24 @@ class ErrorDetail(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': '[ErrorDetail]'}, - '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(ErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -420,7 +390,7 @@ def __init__( self.additional_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.). :ivar error: The error object. @@ -428,24 +398,19 @@ class ErrorResponse(msrest.serialization.Model): """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetail'}, + "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__( - self, - *, - error: Optional["ErrorDetail"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): """ :keyword error: The error object. :paramtype error: ~azure.mgmt.signalr.models.ErrorDetail """ - super(ErrorResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error -class LiveTraceCategory(msrest.serialization.Model): +class LiveTraceCategory(_serialization.Model): """Live trace category configuration of a Microsoft.SignalRService resource. :ivar name: Gets or sets the live trace category's name. @@ -459,17 +424,11 @@ class LiveTraceCategory(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'enabled': {'key': 'enabled', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "enabled": {"key": "enabled", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - enabled: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, enabled: Optional[str] = None, **kwargs): """ :keyword name: Gets or sets the live trace category's name. Available values: ConnectivityLogs, MessagingLogs. @@ -480,12 +439,12 @@ def __init__( Case insensitive. :paramtype enabled: str """ - super(LiveTraceCategory, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.enabled = enabled -class LiveTraceConfiguration(msrest.serialization.Model): +class LiveTraceConfiguration(_serialization.Model): """Live trace configuration of a Microsoft.SignalRService resource. :ivar enabled: Indicates whether or not enable live trace. @@ -500,16 +459,12 @@ class LiveTraceConfiguration(msrest.serialization.Model): """ _attribute_map = { - 'enabled': {'key': 'enabled', 'type': 'str'}, - 'categories': {'key': 'categories', 'type': '[LiveTraceCategory]'}, + "enabled": {"key": "enabled", "type": "str"}, + "categories": {"key": "categories", "type": "[LiveTraceCategory]"}, } def __init__( - self, - *, - enabled: Optional[str] = "false", - categories: Optional[List["LiveTraceCategory"]] = None, - **kwargs + self, *, enabled: str = "false", categories: Optional[List["_models.LiveTraceCategory"]] = None, **kwargs ): """ :keyword enabled: Indicates whether or not enable live trace. @@ -522,12 +477,12 @@ def __init__( :keyword categories: Gets or sets the list of category configurations. :paramtype categories: list[~azure.mgmt.signalr.models.LiveTraceCategory] """ - super(LiveTraceConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.enabled = enabled self.categories = categories -class LogSpecification(msrest.serialization.Model): +class LogSpecification(_serialization.Model): """Specifications of the Logs for Azure Monitoring. :ivar name: Name of the log. @@ -537,35 +492,29 @@ class LogSpecification(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - display_name: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = None, **kwargs): """ :keyword name: Name of the log. :paramtype name: str :keyword display_name: Localized friendly display name of the log. :paramtype display_name: str """ - super(LogSpecification, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.display_name = display_name -class ManagedIdentity(msrest.serialization.Model): +class ManagedIdentity(_serialization.Model): """A class represent managed identities used for request and response. Variables are only populated by the server, and will be ignored when sending a request. - :ivar type: Represents the identity type: systemAssigned, userAssigned, None. Possible values - include: "None", "SystemAssigned", "UserAssigned". + :ivar type: Represents the identity type: systemAssigned, userAssigned, None. Known values are: + "None", "SystemAssigned", and "UserAssigned". :vartype type: str or ~azure.mgmt.signalr.models.ManagedIdentityType :ivar user_assigned_identities: Get or set the user assigned identities. :vartype user_assigned_identities: dict[str, @@ -579,40 +528,40 @@ class ManagedIdentity(msrest.serialization.Model): """ _validation = { - 'principal_id': {'readonly': True}, - 'tenant_id': {'readonly': True}, + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{UserAssignedIdentityProperty}'}, - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentityProperty}"}, + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, } def __init__( self, *, - type: Optional[Union[str, "ManagedIdentityType"]] = None, - user_assigned_identities: Optional[Dict[str, "UserAssignedIdentityProperty"]] = None, + type: Optional[Union[str, "_models.ManagedIdentityType"]] = None, + user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentityProperty"]] = None, **kwargs ): """ - :keyword type: Represents the identity type: systemAssigned, userAssigned, None. Possible - values include: "None", "SystemAssigned", "UserAssigned". + :keyword type: Represents the identity type: systemAssigned, userAssigned, None. Known values + are: "None", "SystemAssigned", and "UserAssigned". :paramtype type: str or ~azure.mgmt.signalr.models.ManagedIdentityType :keyword user_assigned_identities: Get or set the user assigned identities. :paramtype user_assigned_identities: dict[str, ~azure.mgmt.signalr.models.UserAssignedIdentityProperty] """ - super(ManagedIdentity, self).__init__(**kwargs) + super().__init__(**kwargs) self.type = type self.user_assigned_identities = user_assigned_identities self.principal_id = None self.tenant_id = None -class ManagedIdentitySettings(msrest.serialization.Model): +class ManagedIdentitySettings(_serialization.Model): """Managed identity settings for upstream. :ivar resource: The Resource indicating the App ID URI of the target resource. @@ -621,25 +570,20 @@ class ManagedIdentitySettings(msrest.serialization.Model): """ _attribute_map = { - 'resource': {'key': 'resource', 'type': 'str'}, + "resource": {"key": "resource", "type": "str"}, } - def __init__( - self, - *, - resource: Optional[str] = None, - **kwargs - ): + def __init__(self, *, resource: Optional[str] = None, **kwargs): """ :keyword resource: The Resource indicating the App ID URI of the target resource. It also appears in the aud (audience) claim of the issued token. :paramtype resource: str """ - super(ManagedIdentitySettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.resource = resource -class MetricSpecification(msrest.serialization.Model): +class MetricSpecification(_serialization.Model): """Specifications of the Metrics for Azure Monitoring. :ivar name: Name of the metric. @@ -668,14 +612,14 @@ class MetricSpecification(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'display_description': {'key': 'displayDescription', 'type': 'str'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'aggregation_type': {'key': 'aggregationType', 'type': 'str'}, - 'fill_gap_with_zero': {'key': 'fillGapWithZero', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'dimensions': {'key': 'dimensions', 'type': '[Dimension]'}, + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "display_description": {"key": "displayDescription", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "aggregation_type": {"key": "aggregationType", "type": "str"}, + "fill_gap_with_zero": {"key": "fillGapWithZero", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "dimensions": {"key": "dimensions", "type": "[Dimension]"}, } def __init__( @@ -688,7 +632,7 @@ def __init__( aggregation_type: Optional[str] = None, fill_gap_with_zero: Optional[str] = None, category: Optional[str] = None, - dimensions: Optional[List["Dimension"]] = None, + dimensions: Optional[List["_models.Dimension"]] = None, **kwargs ): """ @@ -716,7 +660,7 @@ def __init__( :keyword dimensions: The dimensions of the metrics. :paramtype dimensions: list[~azure.mgmt.signalr.models.Dimension] """ - super(MetricSpecification, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.display_name = display_name self.display_description = display_description @@ -727,7 +671,7 @@ def __init__( self.dimensions = dimensions -class NameAvailability(msrest.serialization.Model): +class NameAvailability(_serialization.Model): """Result of the request to check name availability. It contains a flag and possible reason of failure. :ivar name_available: Indicates whether the name is available or not. @@ -739,9 +683,9 @@ class NameAvailability(msrest.serialization.Model): """ _attribute_map = { - '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"}, + "message": {"key": "message", "type": "str"}, } def __init__( @@ -760,54 +704,48 @@ def __init__( :keyword message: The message of the operation. :paramtype message: str """ - super(NameAvailability, self).__init__(**kwargs) + super().__init__(**kwargs) self.name_available = name_available self.reason = reason self.message = message -class NameAvailabilityParameters(msrest.serialization.Model): +class NameAvailabilityParameters(_serialization.Model): """Data POST-ed to the nameAvailability action. All required parameters must be populated in order to send to Azure. - :ivar type: Required. The resource type. Can be "Microsoft.SignalRService/SignalR" or - "Microsoft.SignalRService/webPubSub". + :ivar type: The resource type. Can be "Microsoft.SignalRService/SignalR" or + "Microsoft.SignalRService/webPubSub". Required. :vartype type: str - :ivar name: Required. The resource name to validate. e.g."my-resource-name". + :ivar name: The resource name to validate. e.g."my-resource-name". Required. :vartype name: str """ _validation = { - 'type': {'required': True}, - 'name': {'required': True}, + "type": {"required": True}, + "name": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - *, - type: str, - name: str, - **kwargs - ): + def __init__(self, *, type: str, name: str, **kwargs): """ - :keyword type: Required. The resource type. Can be "Microsoft.SignalRService/SignalR" or - "Microsoft.SignalRService/webPubSub". + :keyword type: The resource type. Can be "Microsoft.SignalRService/SignalR" or + "Microsoft.SignalRService/webPubSub". Required. :paramtype type: str - :keyword name: Required. The resource name to validate. e.g."my-resource-name". + :keyword name: The resource name to validate. e.g."my-resource-name". Required. :paramtype name: str """ - super(NameAvailabilityParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.type = type self.name = name -class NetworkACL(msrest.serialization.Model): +class NetworkACL(_serialization.Model): """Network ACL. :ivar allow: Allowed request types. The value can be one or more of: ClientConnection, @@ -819,15 +757,15 @@ class NetworkACL(msrest.serialization.Model): """ _attribute_map = { - 'allow': {'key': 'allow', 'type': '[str]'}, - 'deny': {'key': 'deny', 'type': '[str]'}, + "allow": {"key": "allow", "type": "[str]"}, + "deny": {"key": "deny", "type": "[str]"}, } def __init__( self, *, - allow: Optional[List[Union[str, "SignalRRequestType"]]] = None, - deny: Optional[List[Union[str, "SignalRRequestType"]]] = None, + allow: Optional[List[Union[str, "_models.SignalRRequestType"]]] = None, + deny: Optional[List[Union[str, "_models.SignalRRequestType"]]] = None, **kwargs ): """ @@ -838,12 +776,12 @@ def __init__( ServerConnection, RESTAPI. :paramtype deny: list[str or ~azure.mgmt.signalr.models.SignalRRequestType] """ - super(NetworkACL, self).__init__(**kwargs) + super().__init__(**kwargs) self.allow = allow self.deny = deny -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """REST API operation supported by resource provider. :ivar name: Name of the operation with format: {provider}/{resource}/{operation}. @@ -860,11 +798,11 @@ class Operation(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'OperationProperties'}, + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "OperationProperties"}, } def __init__( @@ -872,9 +810,9 @@ def __init__( *, name: Optional[str] = None, is_data_action: Optional[bool] = None, - display: Optional["OperationDisplay"] = None, + display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, - properties: Optional["OperationProperties"] = None, + properties: Optional["_models.OperationProperties"] = None, **kwargs ): """ @@ -890,7 +828,7 @@ def __init__( :keyword properties: Extra Operation properties. :paramtype properties: ~azure.mgmt.signalr.models.OperationProperties """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display @@ -898,7 +836,7 @@ def __init__( self.properties = properties -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The object that describes a operation. :ivar provider: Friendly name of the resource provider. @@ -912,10 +850,10 @@ class OperationDisplay(msrest.serialization.Model): """ _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } def __init__( @@ -937,14 +875,14 @@ def __init__( :keyword description: The localized friendly description for the operation. :paramtype description: str """ - super(OperationDisplay, self).__init__(**kwargs) + super().__init__(**kwargs) self.provider = provider self.resource = resource self.operation = operation self.description = description -class OperationList(msrest.serialization.Model): +class OperationList(_serialization.Model): """Result of the request to list REST API operations. It contains a list of operations. :ivar value: List of operations supported by the resource provider. @@ -955,17 +893,11 @@ class OperationList(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["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: List of operations supported by the resource provider. :paramtype value: list[~azure.mgmt.signalr.models.Operation] @@ -974,12 +906,12 @@ def __init__( It's null for now, added for future use. :paramtype next_link: str """ - super(OperationList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class OperationProperties(msrest.serialization.Model): +class OperationProperties(_serialization.Model): """Extra Operation properties. :ivar service_specification: An object that describes a specification. @@ -987,24 +919,19 @@ class OperationProperties(msrest.serialization.Model): """ _attribute_map = { - 'service_specification': {'key': 'serviceSpecification', 'type': 'ServiceSpecification'}, + "service_specification": {"key": "serviceSpecification", "type": "ServiceSpecification"}, } - def __init__( - self, - *, - service_specification: Optional["ServiceSpecification"] = None, - **kwargs - ): + def __init__(self, *, service_specification: Optional["_models.ServiceSpecification"] = None, **kwargs): """ :keyword service_specification: An object that describes a specification. :paramtype service_specification: ~azure.mgmt.signalr.models.ServiceSpecification """ - super(OperationProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.service_specification = service_specification -class PrivateEndpoint(msrest.serialization.Model): +class PrivateEndpoint(_serialization.Model): """Private endpoint. :ivar id: Full qualified Id of the private endpoint. @@ -1012,20 +939,15 @@ class PrivateEndpoint(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: Full qualified Id of the private endpoint. :paramtype id: str """ - super(PrivateEndpoint, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id @@ -1040,26 +962,26 @@ class PrivateEndpointACL(NetworkACL): :ivar deny: Denied request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI. :vartype deny: list[str or ~azure.mgmt.signalr.models.SignalRRequestType] - :ivar name: Required. Name of the private endpoint connection. + :ivar name: Name of the private endpoint connection. Required. :vartype name: str """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'allow': {'key': 'allow', 'type': '[str]'}, - 'deny': {'key': 'deny', 'type': '[str]'}, - 'name': {'key': 'name', 'type': 'str'}, + "allow": {"key": "allow", "type": "[str]"}, + "deny": {"key": "deny", "type": "[str]"}, + "name": {"key": "name", "type": "str"}, } def __init__( self, *, name: str, - allow: Optional[List[Union[str, "SignalRRequestType"]]] = None, - deny: Optional[List[Union[str, "SignalRRequestType"]]] = None, + allow: Optional[List[Union[str, "_models.SignalRRequestType"]]] = None, + deny: Optional[List[Union[str, "_models.SignalRRequestType"]]] = None, **kwargs ): """ @@ -1069,10 +991,10 @@ def __init__( :keyword deny: Denied request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI. :paramtype deny: list[str or ~azure.mgmt.signalr.models.SignalRRequestType] - :keyword name: Required. Name of the private endpoint connection. + :keyword name: Name of the private endpoint connection. Required. :paramtype name: str """ - super(PrivateEndpointACL, self).__init__(allow=allow, deny=deny, **kwargs) + super().__init__(allow=allow, deny=deny, **kwargs) self.name = name @@ -1089,9 +1011,8 @@ class PrivateEndpointConnection(ProxyResource): :vartype type: str :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.signalr.models.SystemData - :ivar provisioning_state: Provisioning state of the resource. Possible values include: - "Unknown", "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", - "Moving". + :ivar provisioning_state: Provisioning state of the resource. Known values are: "Unknown", + "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", and "Moving". :vartype provisioning_state: str or ~azure.mgmt.signalr.models.ProvisioningState :ivar private_endpoint: Private endpoint. :vartype private_endpoint: ~azure.mgmt.signalr.models.PrivateEndpoint @@ -1104,30 +1025,33 @@ class PrivateEndpointConnection(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'group_ids': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "group_ids": {"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'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'}, - 'group_ids': {'key': 'properties.groupIds', 'type': '[str]'}, - 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpoint"}, + "group_ids": {"key": "properties.groupIds", "type": "[str]"}, + "private_link_service_connection_state": { + "key": "properties.privateLinkServiceConnectionState", + "type": "PrivateLinkServiceConnectionState", + }, } def __init__( self, *, - private_endpoint: Optional["PrivateEndpoint"] = None, - private_link_service_connection_state: Optional["PrivateLinkServiceConnectionState"] = None, + private_endpoint: Optional["_models.PrivateEndpoint"] = None, + private_link_service_connection_state: Optional["_models.PrivateLinkServiceConnectionState"] = None, **kwargs ): """ @@ -1138,7 +1062,7 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.signalr.models.PrivateLinkServiceConnectionState """ - super(PrivateEndpointConnection, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.provisioning_state = None self.private_endpoint = private_endpoint @@ -1146,7 +1070,7 @@ def __init__( self.private_link_service_connection_state = private_link_service_connection_state -class PrivateEndpointConnectionList(msrest.serialization.Model): +class PrivateEndpointConnectionList(_serialization.Model): """A list of private endpoint connections. :ivar value: The list of the private endpoint connections. @@ -1158,14 +1082,14 @@ class PrivateEndpointConnectionList(msrest.serialization.Model): """ _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, *, - value: Optional[List["PrivateEndpointConnection"]] = None, + value: Optional[List["_models.PrivateEndpointConnection"]] = None, next_link: Optional[str] = None, **kwargs ): @@ -1177,7 +1101,7 @@ def __init__( maximum page size. :paramtype next_link: str """ - super(PrivateEndpointConnectionList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -1206,19 +1130,22 @@ class PrivateLinkResource(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'}, - 'group_id': {'key': 'properties.groupId', 'type': 'str'}, - 'required_members': {'key': 'properties.requiredMembers', 'type': '[str]'}, - 'required_zone_names': {'key': 'properties.requiredZoneNames', 'type': '[str]'}, - 'shareable_private_link_resource_types': {'key': 'properties.shareablePrivateLinkResourceTypes', 'type': '[ShareablePrivateLinkResourceType]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "group_id": {"key": "properties.groupId", "type": "str"}, + "required_members": {"key": "properties.requiredMembers", "type": "[str]"}, + "required_zone_names": {"key": "properties.requiredZoneNames", "type": "[str]"}, + "shareable_private_link_resource_types": { + "key": "properties.shareablePrivateLinkResourceTypes", + "type": "[ShareablePrivateLinkResourceType]", + }, } def __init__( @@ -1227,7 +1154,7 @@ def __init__( group_id: Optional[str] = None, required_members: Optional[List[str]] = None, required_zone_names: Optional[List[str]] = None, - shareable_private_link_resource_types: Optional[List["ShareablePrivateLinkResourceType"]] = None, + shareable_private_link_resource_types: Optional[List["_models.ShareablePrivateLinkResourceType"]] = None, **kwargs ): """ @@ -1242,14 +1169,14 @@ def __init__( :paramtype shareable_private_link_resource_types: list[~azure.mgmt.signalr.models.ShareablePrivateLinkResourceType] """ - super(PrivateLinkResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.group_id = group_id self.required_members = required_members self.required_zone_names = required_zone_names self.shareable_private_link_resource_types = shareable_private_link_resource_types -class PrivateLinkResourceList(msrest.serialization.Model): +class PrivateLinkResourceList(_serialization.Model): """Contains a list of PrivateLinkResource and a possible link to query more results. :ivar value: List of PrivateLinkResource. @@ -1260,16 +1187,12 @@ class PrivateLinkResourceList(msrest.serialization.Model): """ _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, - *, - value: Optional[List["PrivateLinkResource"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: List of PrivateLinkResource. @@ -1279,16 +1202,16 @@ def __init__( It's null for now, added for future use. :paramtype next_link: str """ - super(PrivateLinkResourceList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class PrivateLinkServiceConnectionState(msrest.serialization.Model): +class PrivateLinkServiceConnectionState(_serialization.Model): """Connection state of the private endpoint connection. :ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner - of the service. Possible values include: "Pending", "Approved", "Rejected", "Disconnected". + of the service. Known values are: "Pending", "Approved", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.signalr.models.PrivateLinkServiceConnectionStatus :ivar description: The reason for approval/rejection of the connection. :vartype description: str @@ -1298,23 +1221,22 @@ class PrivateLinkServiceConnectionState(msrest.serialization.Model): """ _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: Optional[Union[str, "PrivateLinkServiceConnectionStatus"]] = None, + status: Optional[Union[str, "_models.PrivateLinkServiceConnectionStatus"]] = None, description: Optional[str] = None, actions_required: Optional[str] = None, **kwargs ): """ :keyword status: Indicates whether the connection has been Approved/Rejected/Removed by the - owner of the service. Possible values include: "Pending", "Approved", "Rejected", - "Disconnected". + owner of the service. Known values are: "Pending", "Approved", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.signalr.models.PrivateLinkServiceConnectionStatus :keyword description: The reason for approval/rejection of the connection. :paramtype description: str @@ -1322,40 +1244,34 @@ def __init__( updates on the consumer. :paramtype actions_required: str """ - super(PrivateLinkServiceConnectionState, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.description = description self.actions_required = actions_required -class RegenerateKeyParameters(msrest.serialization.Model): +class RegenerateKeyParameters(_serialization.Model): """Parameters describes the request to regenerate access keys. - :ivar key_type: The type of access key. Possible values include: "Primary", "Secondary", - "Salt". + :ivar key_type: The type of access key. Known values are: "Primary", "Secondary", and "Salt". :vartype key_type: str or ~azure.mgmt.signalr.models.KeyType """ _attribute_map = { - 'key_type': {'key': 'keyType', 'type': 'str'}, + "key_type": {"key": "keyType", "type": "str"}, } - def __init__( - self, - *, - key_type: Optional[Union[str, "KeyType"]] = None, - **kwargs - ): + def __init__(self, *, key_type: Optional[Union[str, "_models.KeyType"]] = None, **kwargs): """ - :keyword key_type: The type of access key. Possible values include: "Primary", "Secondary", + :keyword key_type: The type of access key. Known values are: "Primary", "Secondary", and "Salt". :paramtype key_type: str or ~azure.mgmt.signalr.models.KeyType """ - super(RegenerateKeyParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.key_type = key_type -class ResourceLogCategory(msrest.serialization.Model): +class ResourceLogCategory(_serialization.Model): """Resource log category configuration of a Microsoft.SignalRService resource. :ivar name: Gets or sets the resource log category's name. @@ -1369,17 +1285,11 @@ class ResourceLogCategory(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'enabled': {'key': 'enabled', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "enabled": {"key": "enabled", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - enabled: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, enabled: Optional[str] = None, **kwargs): """ :keyword name: Gets or sets the resource log category's name. Available values: ConnectivityLogs, MessagingLogs. @@ -1390,12 +1300,12 @@ def __init__( Case insensitive. :paramtype enabled: str """ - super(ResourceLogCategory, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.enabled = enabled -class ResourceLogConfiguration(msrest.serialization.Model): +class ResourceLogConfiguration(_serialization.Model): """Resource log configuration of a Microsoft.SignalRService resource. :ivar categories: Gets or sets the list of category configurations. @@ -1403,24 +1313,19 @@ class ResourceLogConfiguration(msrest.serialization.Model): """ _attribute_map = { - 'categories': {'key': 'categories', 'type': '[ResourceLogCategory]'}, + "categories": {"key": "categories", "type": "[ResourceLogCategory]"}, } - def __init__( - self, - *, - categories: Optional[List["ResourceLogCategory"]] = None, - **kwargs - ): + def __init__(self, *, categories: Optional[List["_models.ResourceLogCategory"]] = None, **kwargs): """ :keyword categories: Gets or sets the list of category configurations. :paramtype categories: list[~azure.mgmt.signalr.models.ResourceLogCategory] """ - super(ResourceLogConfiguration, self).__init__(**kwargs) + super().__init__(**kwargs) self.categories = categories -class ResourceReference(msrest.serialization.Model): +class ResourceReference(_serialization.Model): """Reference to a resource. :ivar id: Resource ID. @@ -1428,91 +1333,88 @@ class ResourceReference(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. :paramtype id: str """ - super(ResourceReference, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id -class ResourceSku(msrest.serialization.Model): +class ResourceSku(_serialization.Model): """The billing information of the resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the SKU. Required. - - Allowed values: Standard_S1, Free_F1. + :ivar name: The name of the SKU. Required. + + Allowed values: Standard_S1, Free_F1, Premium_P1. Required. :vartype name: str :ivar tier: Optional tier of this particular SKU. 'Standard' or 'Free'. - - ``Basic`` is deprecated, use ``Standard`` instead. Possible values include: "Free", "Basic", - "Standard", "Premium". + + ``Basic`` is deprecated, use ``Standard`` instead. Known values are: "Free", "Basic", + "Standard", and "Premium". :vartype tier: str or ~azure.mgmt.signalr.models.SignalRSkuTier :ivar size: Not used. Retained for future use. :vartype size: str :ivar family: Not used. Retained for future use. :vartype family: str :ivar capacity: Optional, integer. The unit count of the resource. 1 by default. - + If present, following values are allowed: - Free: 1 - Standard: 1,2,5,10,20,50,100. + Free: 1; + Standard: 1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100; + Premium: 1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100;. :vartype capacity: int """ _validation = { - 'name': {'required': True}, - 'size': {'readonly': True}, - 'family': {'readonly': True}, + "name": {"required": True}, + "size": {"readonly": True}, + "family": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'tier': {'key': 'tier', 'type': 'str'}, - 'size': {'key': 'size', 'type': 'str'}, - 'family': {'key': 'family', 'type': 'str'}, - 'capacity': {'key': 'capacity', 'type': 'int'}, + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + "size": {"key": "size", "type": "str"}, + "family": {"key": "family", "type": "str"}, + "capacity": {"key": "capacity", "type": "int"}, } def __init__( self, *, name: str, - tier: Optional[Union[str, "SignalRSkuTier"]] = None, + tier: Optional[Union[str, "_models.SignalRSkuTier"]] = None, capacity: Optional[int] = None, **kwargs ): """ - :keyword name: Required. The name of the SKU. Required. - - Allowed values: Standard_S1, Free_F1. + :keyword name: The name of the SKU. Required. + + Allowed values: Standard_S1, Free_F1, Premium_P1. Required. :paramtype name: str :keyword tier: Optional tier of this particular SKU. 'Standard' or 'Free'. - - ``Basic`` is deprecated, use ``Standard`` instead. Possible values include: "Free", "Basic", - "Standard", "Premium". + + ``Basic`` is deprecated, use ``Standard`` instead. Known values are: "Free", "Basic", + "Standard", and "Premium". :paramtype tier: str or ~azure.mgmt.signalr.models.SignalRSkuTier :keyword capacity: Optional, integer. The unit count of the resource. 1 by default. - + If present, following values are allowed: - Free: 1 - Standard: 1,2,5,10,20,50,100. + Free: 1; + Standard: 1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100; + Premium: 1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100;. :paramtype capacity: int """ - super(ResourceSku, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.tier = tier self.size = None @@ -1520,7 +1422,53 @@ def __init__( self.capacity = capacity -class ServerlessUpstreamSettings(msrest.serialization.Model): +class ServerlessSettings(_serialization.Model): + """Serverless settings. + + :ivar connection_timeout_in_seconds: Gets or sets Client Connection Timeout. Optional to be + set. + Value in seconds. + Default value is 30 seconds. + Customer should set the timeout to a shorter period if messages are expected to be sent in + shorter intervals, + and want the client to disconnect more quickly after the last message is sent. + You can set the timeout to a longer period if messages are expected to be sent in longer + intervals, + and they want to keep the same client connection alive during this session. + The service considers the client disconnected if it hasn't received a message (including + keep-alive) in this interval. + :vartype connection_timeout_in_seconds: int + """ + + _validation = { + "connection_timeout_in_seconds": {"maximum": 120, "minimum": 1}, + } + + _attribute_map = { + "connection_timeout_in_seconds": {"key": "connectionTimeoutInSeconds", "type": "int"}, + } + + def __init__(self, *, connection_timeout_in_seconds: int = 30, **kwargs): + """ + :keyword connection_timeout_in_seconds: Gets or sets Client Connection Timeout. Optional to be + set. + Value in seconds. + Default value is 30 seconds. + Customer should set the timeout to a shorter period if messages are expected to be sent in + shorter intervals, + and want the client to disconnect more quickly after the last message is sent. + You can set the timeout to a longer period if messages are expected to be sent in longer + intervals, + and they want to keep the same client connection alive during this session. + The service considers the client disconnected if it hasn't received a message (including + keep-alive) in this interval. + :paramtype connection_timeout_in_seconds: int + """ + super().__init__(**kwargs) + self.connection_timeout_in_seconds = connection_timeout_in_seconds + + +class ServerlessUpstreamSettings(_serialization.Model): """The settings for the Upstream when the service is in server-less mode. :ivar templates: Gets or sets the list of Upstream URL templates. Order matters, and the first @@ -1529,25 +1477,20 @@ class ServerlessUpstreamSettings(msrest.serialization.Model): """ _attribute_map = { - 'templates': {'key': 'templates', 'type': '[UpstreamTemplate]'}, + "templates": {"key": "templates", "type": "[UpstreamTemplate]"}, } - def __init__( - self, - *, - templates: Optional[List["UpstreamTemplate"]] = None, - **kwargs - ): + def __init__(self, *, templates: Optional[List["_models.UpstreamTemplate"]] = None, **kwargs): """ :keyword templates: Gets or sets the list of Upstream URL templates. Order matters, and the first matching template takes effects. :paramtype templates: list[~azure.mgmt.signalr.models.UpstreamTemplate] """ - super(ServerlessUpstreamSettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.templates = templates -class ServiceSpecification(msrest.serialization.Model): +class ServiceSpecification(_serialization.Model): """An object that describes a specification. :ivar metric_specifications: Specifications of the Metrics for Azure Monitoring. @@ -1557,15 +1500,15 @@ class ServiceSpecification(msrest.serialization.Model): """ _attribute_map = { - 'metric_specifications': {'key': 'metricSpecifications', 'type': '[MetricSpecification]'}, - 'log_specifications': {'key': 'logSpecifications', 'type': '[LogSpecification]'}, + "metric_specifications": {"key": "metricSpecifications", "type": "[MetricSpecification]"}, + "log_specifications": {"key": "logSpecifications", "type": "[LogSpecification]"}, } def __init__( self, *, - metric_specifications: Optional[List["MetricSpecification"]] = None, - log_specifications: Optional[List["LogSpecification"]] = None, + metric_specifications: Optional[List["_models.MetricSpecification"]] = None, + log_specifications: Optional[List["_models.LogSpecification"]] = None, **kwargs ): """ @@ -1574,12 +1517,12 @@ def __init__( :keyword log_specifications: Specifications of the Logs for Azure Monitoring. :paramtype log_specifications: list[~azure.mgmt.signalr.models.LogSpecification] """ - super(ServiceSpecification, self).__init__(**kwargs) + super().__init__(**kwargs) self.metric_specifications = metric_specifications self.log_specifications = log_specifications -class ShareablePrivateLinkResourceProperties(msrest.serialization.Model): +class ShareablePrivateLinkResourceProperties(_serialization.Model): """Describes the properties of a resource type that has been onboarded to private link service. :ivar description: The description of the resource type that has been onboarded to private link @@ -1594,18 +1537,13 @@ class ShareablePrivateLinkResourceProperties(msrest.serialization.Model): """ _attribute_map = { - 'description': {'key': 'description', 'type': 'str'}, - 'group_id': {'key': 'groupId', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "description": {"key": "description", "type": "str"}, + "group_id": {"key": "groupId", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( - self, - *, - description: Optional[str] = None, - group_id: Optional[str] = None, - type: Optional[str] = None, - **kwargs + self, *, description: Optional[str] = None, group_id: Optional[str] = None, type: Optional[str] = None, **kwargs ): """ :keyword description: The description of the resource type that has been onboarded to private @@ -1618,13 +1556,13 @@ def __init__( link service. :paramtype type: str """ - super(ShareablePrivateLinkResourceProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.description = description self.group_id = group_id self.type = type -class ShareablePrivateLinkResourceType(msrest.serialization.Model): +class ShareablePrivateLinkResourceType(_serialization.Model): """Describes a resource type that has been onboarded to private link service. :ivar name: The name of the resource type that has been onboarded to private link service. @@ -1635,15 +1573,15 @@ class ShareablePrivateLinkResourceType(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'ShareablePrivateLinkResourceProperties'}, + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "ShareablePrivateLinkResourceProperties"}, } def __init__( self, *, name: Optional[str] = None, - properties: Optional["ShareablePrivateLinkResourceProperties"] = None, + properties: Optional["_models.ShareablePrivateLinkResourceProperties"] = None, **kwargs ): """ @@ -1653,7 +1591,7 @@ def __init__( private link service. :paramtype properties: ~azure.mgmt.signalr.models.ShareablePrivateLinkResourceProperties """ - super(ShareablePrivateLinkResourceType, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.properties = properties @@ -1677,37 +1615,36 @@ class SharedPrivateLinkResource(ProxyResource): :ivar private_link_resource_id: The resource id of the resource the shared private link resource is for. :vartype private_link_resource_id: str - :ivar provisioning_state: Provisioning state of the resource. Possible values include: - "Unknown", "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", - "Moving". + :ivar provisioning_state: Provisioning state of the resource. Known values are: "Unknown", + "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", and "Moving". :vartype provisioning_state: str or ~azure.mgmt.signalr.models.ProvisioningState :ivar request_message: The request message for requesting approval of the shared private link resource. :vartype request_message: str - :ivar status: Status of the shared private link resource. Possible values include: "Pending", - "Approved", "Rejected", "Disconnected", "Timeout". + :ivar status: Status of the shared private link resource. Known values are: "Pending", + "Approved", "Rejected", "Disconnected", and "Timeout". :vartype status: str or ~azure.mgmt.signalr.models.SharedPrivateLinkResourceStatus """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'status': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "status": {"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'}, - 'group_id': {'key': 'properties.groupId', 'type': 'str'}, - 'private_link_resource_id': {'key': 'properties.privateLinkResourceId', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'request_message': {'key': 'properties.requestMessage', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "group_id": {"key": "properties.groupId", "type": "str"}, + "private_link_resource_id": {"key": "properties.privateLinkResourceId", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "request_message": {"key": "properties.requestMessage", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, } def __init__( @@ -1729,7 +1666,7 @@ def __init__( link resource. :paramtype request_message: str """ - super(SharedPrivateLinkResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.group_id = group_id self.private_link_resource_id = private_link_resource_id @@ -1738,7 +1675,7 @@ def __init__( self.status = None -class SharedPrivateLinkResourceList(msrest.serialization.Model): +class SharedPrivateLinkResourceList(_serialization.Model): """A list of shared private link resources. :ivar value: The list of the shared private link resources. @@ -1750,14 +1687,14 @@ class SharedPrivateLinkResourceList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[SharedPrivateLinkResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[SharedPrivateLinkResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["SharedPrivateLinkResource"]] = None, + value: Optional[List["_models.SharedPrivateLinkResource"]] = None, next_link: Optional[str] = None, **kwargs ): @@ -1769,12 +1706,12 @@ def __init__( maximum page size. :paramtype next_link: str """ - super(SharedPrivateLinkResourceList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class SignalRCorsSettings(msrest.serialization.Model): +class SignalRCorsSettings(_serialization.Model): """Cross-Origin Resource Sharing (CORS) settings. :ivar allowed_origins: Gets or sets the list of origins that should be allowed to make @@ -1784,33 +1721,28 @@ class SignalRCorsSettings(msrest.serialization.Model): """ _attribute_map = { - 'allowed_origins': {'key': 'allowedOrigins', 'type': '[str]'}, + "allowed_origins": {"key": "allowedOrigins", "type": "[str]"}, } - def __init__( - self, - *, - allowed_origins: Optional[List[str]] = None, - **kwargs - ): + def __init__(self, *, allowed_origins: Optional[List[str]] = None, **kwargs): """ :keyword allowed_origins: Gets or sets the list of origins that should be allowed to make cross-origin calls (for example: http://example.com:12345). Use "*" to allow all. If omitted, allow all by default. :paramtype allowed_origins: list[str] """ - super(SignalRCorsSettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.allowed_origins = allowed_origins -class SignalRFeature(msrest.serialization.Model): +class SignalRFeature(_serialization.Model): """Feature of a resource, which controls the runtime behavior. All required parameters must be populated in order to send to Azure. - :ivar flag: Required. FeatureFlags is the supported features of Azure SignalR service. - - + :ivar flag: FeatureFlags is the supported features of Azure SignalR service. + + * ServiceMode: Flag for backend server for SignalR service. Values allowed: "Default": have your own backend server; "Serverless": your application doesn't have a backend server; "Classic": for backward compatibility. Support both Default and Serverless mode but not @@ -1823,39 +1755,39 @@ class SignalRFeature(msrest.serialization.Model): service, it will give you live traces in real time, it will be helpful when you developing your own Azure SignalR based web application or self-troubleshooting some issues. Please note that live traces are counted as outbound messages that will be charged. Values allowed: - "true"/"false", to enable/disable live trace feature. Possible values include: "ServiceMode", - "EnableConnectivityLogs", "EnableMessagingLogs", "EnableLiveTrace". + "true"/"false", to enable/disable live trace feature. Required. Known values are: + "ServiceMode", "EnableConnectivityLogs", "EnableMessagingLogs", and "EnableLiveTrace". :vartype flag: str or ~azure.mgmt.signalr.models.FeatureFlags - :ivar value: Required. Value of the feature flag. See Azure SignalR service document - https://docs.microsoft.com/azure/azure-signalr/ for allowed values. + :ivar value: Value of the feature flag. See Azure SignalR service document + https://docs.microsoft.com/azure/azure-signalr/ for allowed values. Required. :vartype value: str :ivar properties: Optional properties related to this feature. :vartype properties: dict[str, str] """ _validation = { - 'flag': {'required': True}, - 'value': {'required': True, 'max_length': 128, 'min_length': 1}, + "flag": {"required": True}, + "value": {"required": True, "max_length": 128, "min_length": 1}, } _attribute_map = { - 'flag': {'key': 'flag', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, + "flag": {"key": "flag", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, } def __init__( self, *, - flag: Union[str, "FeatureFlags"], + flag: Union[str, "_models.FeatureFlags"], value: str, properties: Optional[Dict[str, str]] = None, **kwargs ): """ - :keyword flag: Required. FeatureFlags is the supported features of Azure SignalR service. - - + :keyword flag: FeatureFlags is the supported features of Azure SignalR service. + + * ServiceMode: Flag for backend server for SignalR service. Values allowed: "Default": have your own backend server; "Serverless": your application doesn't have a backend server; "Classic": for backward compatibility. Support both Default and Serverless mode but not @@ -1868,22 +1800,22 @@ def __init__( service, it will give you live traces in real time, it will be helpful when you developing your own Azure SignalR based web application or self-troubleshooting some issues. Please note that live traces are counted as outbound messages that will be charged. Values allowed: - "true"/"false", to enable/disable live trace feature. Possible values include: "ServiceMode", - "EnableConnectivityLogs", "EnableMessagingLogs", "EnableLiveTrace". + "true"/"false", to enable/disable live trace feature. Required. Known values are: + "ServiceMode", "EnableConnectivityLogs", "EnableMessagingLogs", and "EnableLiveTrace". :paramtype flag: str or ~azure.mgmt.signalr.models.FeatureFlags - :keyword value: Required. Value of the feature flag. See Azure SignalR service document - https://docs.microsoft.com/azure/azure-signalr/ for allowed values. + :keyword value: Value of the feature flag. See Azure SignalR service document + https://docs.microsoft.com/azure/azure-signalr/ for allowed values. Required. :paramtype value: str :keyword properties: Optional properties related to this feature. :paramtype properties: dict[str, str] """ - super(SignalRFeature, self).__init__(**kwargs) + super().__init__(**kwargs) self.flag = flag self.value = value self.properties = properties -class SignalRKeys(msrest.serialization.Model): +class SignalRKeys(_serialization.Model): """A class represents the access keys of the resource. :ivar primary_key: The primary access key. @@ -1897,10 +1829,10 @@ class SignalRKeys(msrest.serialization.Model): """ _attribute_map = { - 'primary_key': {'key': 'primaryKey', 'type': 'str'}, - 'secondary_key': {'key': 'secondaryKey', 'type': 'str'}, - 'primary_connection_string': {'key': 'primaryConnectionString', 'type': 'str'}, - 'secondary_connection_string': {'key': 'secondaryConnectionString', 'type': 'str'}, + "primary_key": {"key": "primaryKey", "type": "str"}, + "secondary_key": {"key": "secondaryKey", "type": "str"}, + "primary_connection_string": {"key": "primaryConnectionString", "type": "str"}, + "secondary_connection_string": {"key": "secondaryConnectionString", "type": "str"}, } def __init__( @@ -1922,17 +1854,17 @@ def __init__( :keyword secondary_connection_string: Connection string constructed via the secondaryKey. :paramtype secondary_connection_string: str """ - super(SignalRKeys, self).__init__(**kwargs) + super().__init__(**kwargs) self.primary_key = primary_key self.secondary_key = secondary_key self.primary_connection_string = primary_connection_string self.secondary_connection_string = secondary_connection_string -class SignalRNetworkACLs(msrest.serialization.Model): +class SignalRNetworkACLs(_serialization.Model): """Network ACLs for the resource. - :ivar default_action: Azure Networking ACL Action. Possible values include: "Allow", "Deny". + :ivar default_action: Azure Networking ACL Action. Known values are: "Allow" and "Deny". :vartype default_action: str or ~azure.mgmt.signalr.models.ACLAction :ivar public_network: Network ACL. :vartype public_network: ~azure.mgmt.signalr.models.NetworkACL @@ -1941,28 +1873,28 @@ class SignalRNetworkACLs(msrest.serialization.Model): """ _attribute_map = { - 'default_action': {'key': 'defaultAction', 'type': 'str'}, - 'public_network': {'key': 'publicNetwork', 'type': 'NetworkACL'}, - 'private_endpoints': {'key': 'privateEndpoints', 'type': '[PrivateEndpointACL]'}, + "default_action": {"key": "defaultAction", "type": "str"}, + "public_network": {"key": "publicNetwork", "type": "NetworkACL"}, + "private_endpoints": {"key": "privateEndpoints", "type": "[PrivateEndpointACL]"}, } def __init__( self, *, - default_action: Optional[Union[str, "ACLAction"]] = None, - public_network: Optional["NetworkACL"] = None, - private_endpoints: Optional[List["PrivateEndpointACL"]] = None, + default_action: Optional[Union[str, "_models.ACLAction"]] = None, + public_network: Optional["_models.NetworkACL"] = None, + private_endpoints: Optional[List["_models.PrivateEndpointACL"]] = None, **kwargs ): """ - :keyword default_action: Azure Networking ACL Action. Possible values include: "Allow", "Deny". + :keyword default_action: Azure Networking ACL Action. Known values are: "Allow" and "Deny". :paramtype default_action: str or ~azure.mgmt.signalr.models.ACLAction :keyword public_network: Network ACL. :paramtype public_network: ~azure.mgmt.signalr.models.NetworkACL :keyword private_endpoints: ACLs for requests from private endpoints. :paramtype private_endpoints: list[~azure.mgmt.signalr.models.PrivateEndpointACL] """ - super(SignalRNetworkACLs, self).__init__(**kwargs) + super().__init__(**kwargs) self.default_action = default_action self.public_network = public_network self.private_endpoints = private_endpoints @@ -1982,46 +1914,39 @@ class TrackedResource(Resource): :ivar location: The GEO location of the resource. e.g. West US | East US | North Central US | South Central US. :vartype location: str - :ivar tags: A set of tags. Tags of the service which is a list of key value pairs that describe - the resource. + :ivar tags: Tags of the service which is a list of key value pairs that describe the resource. :vartype tags: dict[str, str] """ _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'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, } - def __init__( - self, - *, - location: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): + def __init__(self, *, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, **kwargs): """ :keyword location: The GEO location of the resource. e.g. West US | East US | North Central US | South Central US. :paramtype location: str - :keyword tags: A set of tags. Tags of the service which is a list of key value pairs that - describe the resource. + :keyword tags: Tags of the service which is a list of key value pairs that describe the + resource. :paramtype tags: dict[str, str] """ - super(TrackedResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.location = location self.tags = tags -class SignalRResource(TrackedResource): +class SignalRResource(TrackedResource): # pylint: disable=too-many-instance-attributes """A class represent a resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2035,21 +1960,19 @@ class SignalRResource(TrackedResource): :ivar location: The GEO location of the resource. e.g. West US | East US | North Central US | South Central US. :vartype location: str - :ivar tags: A set of tags. Tags of the service which is a list of key value pairs that describe - the resource. + :ivar tags: Tags of the service which is a list of key value pairs that describe the resource. :vartype tags: dict[str, str] :ivar sku: The billing information of the resource. :vartype sku: ~azure.mgmt.signalr.models.ResourceSku - :ivar kind: The kind of the service, it can be SignalR or RawWebSockets. Possible values - include: "SignalR", "RawWebSockets". + :ivar kind: The kind of the service, it can be SignalR or RawWebSockets. Known values are: + "SignalR" and "RawWebSockets". :vartype kind: str or ~azure.mgmt.signalr.models.ServiceKind :ivar identity: A class represent managed identities used for request and response. :vartype identity: ~azure.mgmt.signalr.models.ManagedIdentity :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.signalr.models.SystemData - :ivar provisioning_state: Provisioning state of the resource. Possible values include: - "Unknown", "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", - "Moving". + :ivar provisioning_state: Provisioning state of the resource. Known values are: "Unknown", + "Succeeded", "Failed", "Canceled", "Running", "Creating", "Updating", "Deleting", and "Moving". :vartype provisioning_state: str or ~azure.mgmt.signalr.models.ProvisioningState :ivar external_ip: The publicly accessible IP of the resource. :vartype external_ip: str @@ -2075,7 +1998,7 @@ class SignalRResource(TrackedResource): :ivar host_name_prefix: Deprecated. :vartype host_name_prefix: str :ivar features: List of the featureFlags. - + FeatureFlags that are not included in the parameters for the update operation will not be modified. And the response will only include featureFlags that are explicitly set. @@ -2091,6 +2014,8 @@ class SignalRResource(TrackedResource): :vartype resource_log_configuration: ~azure.mgmt.signalr.models.ResourceLogConfiguration :ivar cors: Cross-Origin Resource Sharing (CORS) settings. :vartype cors: ~azure.mgmt.signalr.models.SignalRCorsSettings + :ivar serverless: Serverless settings. + :vartype serverless: ~azure.mgmt.signalr.models.ServerlessSettings :ivar upstream: The settings for the Upstream when the service is in server-less mode. :vartype upstream: ~azure.mgmt.signalr.models.ServerlessUpstreamSettings :ivar network_ac_ls: Network ACLs for the resource. @@ -2111,90 +2036,101 @@ class SignalRResource(TrackedResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'external_ip': {'readonly': True}, - 'host_name': {'readonly': True}, - 'public_port': {'readonly': True}, - 'server_port': {'readonly': True}, - 'version': {'readonly': True}, - 'private_endpoint_connections': {'readonly': True}, - 'shared_private_link_resources': {'readonly': True}, - 'host_name_prefix': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "external_ip": {"readonly": True}, + "host_name": {"readonly": True}, + "public_port": {"readonly": True}, + "server_port": {"readonly": True}, + "version": {"readonly": True}, + "private_endpoint_connections": {"readonly": True}, + "shared_private_link_resources": {"readonly": True}, + "host_name_prefix": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'sku': {'key': 'sku', 'type': 'ResourceSku'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'identity': {'key': 'identity', 'type': 'ManagedIdentity'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'external_ip': {'key': 'properties.externalIP', 'type': 'str'}, - 'host_name': {'key': 'properties.hostName', 'type': 'str'}, - 'public_port': {'key': 'properties.publicPort', 'type': 'int'}, - 'server_port': {'key': 'properties.serverPort', 'type': 'int'}, - 'version': {'key': 'properties.version', 'type': 'str'}, - 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[PrivateEndpointConnection]'}, - 'shared_private_link_resources': {'key': 'properties.sharedPrivateLinkResources', 'type': '[SharedPrivateLinkResource]'}, - 'tls': {'key': 'properties.tls', 'type': 'SignalRTlsSettings'}, - 'host_name_prefix': {'key': 'properties.hostNamePrefix', 'type': 'str'}, - 'features': {'key': 'properties.features', 'type': '[SignalRFeature]'}, - 'live_trace_configuration': {'key': 'properties.liveTraceConfiguration', 'type': 'LiveTraceConfiguration'}, - 'resource_log_configuration': {'key': 'properties.resourceLogConfiguration', 'type': 'ResourceLogConfiguration'}, - 'cors': {'key': 'properties.cors', 'type': 'SignalRCorsSettings'}, - 'upstream': {'key': 'properties.upstream', 'type': 'ServerlessUpstreamSettings'}, - 'network_ac_ls': {'key': 'properties.networkACLs', 'type': 'SignalRNetworkACLs'}, - 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, - 'disable_local_auth': {'key': 'properties.disableLocalAuth', 'type': 'bool'}, - 'disable_aad_auth': {'key': 'properties.disableAadAuth', 'type': 'bool'}, - } - - def __init__( + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "sku": {"key": "sku", "type": "ResourceSku"}, + "kind": {"key": "kind", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedIdentity"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "external_ip": {"key": "properties.externalIP", "type": "str"}, + "host_name": {"key": "properties.hostName", "type": "str"}, + "public_port": {"key": "properties.publicPort", "type": "int"}, + "server_port": {"key": "properties.serverPort", "type": "int"}, + "version": {"key": "properties.version", "type": "str"}, + "private_endpoint_connections": { + "key": "properties.privateEndpointConnections", + "type": "[PrivateEndpointConnection]", + }, + "shared_private_link_resources": { + "key": "properties.sharedPrivateLinkResources", + "type": "[SharedPrivateLinkResource]", + }, + "tls": {"key": "properties.tls", "type": "SignalRTlsSettings"}, + "host_name_prefix": {"key": "properties.hostNamePrefix", "type": "str"}, + "features": {"key": "properties.features", "type": "[SignalRFeature]"}, + "live_trace_configuration": {"key": "properties.liveTraceConfiguration", "type": "LiveTraceConfiguration"}, + "resource_log_configuration": { + "key": "properties.resourceLogConfiguration", + "type": "ResourceLogConfiguration", + }, + "cors": {"key": "properties.cors", "type": "SignalRCorsSettings"}, + "serverless": {"key": "properties.serverless", "type": "ServerlessSettings"}, + "upstream": {"key": "properties.upstream", "type": "ServerlessUpstreamSettings"}, + "network_ac_ls": {"key": "properties.networkACLs", "type": "SignalRNetworkACLs"}, + "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, + "disable_local_auth": {"key": "properties.disableLocalAuth", "type": "bool"}, + "disable_aad_auth": {"key": "properties.disableAadAuth", "type": "bool"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, - sku: Optional["ResourceSku"] = None, - kind: Optional[Union[str, "ServiceKind"]] = None, - identity: Optional["ManagedIdentity"] = None, - tls: Optional["SignalRTlsSettings"] = None, - features: Optional[List["SignalRFeature"]] = None, - live_trace_configuration: Optional["LiveTraceConfiguration"] = None, - resource_log_configuration: Optional["ResourceLogConfiguration"] = None, - cors: Optional["SignalRCorsSettings"] = None, - upstream: Optional["ServerlessUpstreamSettings"] = None, - network_ac_ls: Optional["SignalRNetworkACLs"] = None, - public_network_access: Optional[str] = "Enabled", - disable_local_auth: Optional[bool] = False, - disable_aad_auth: Optional[bool] = False, + sku: Optional["_models.ResourceSku"] = None, + kind: Optional[Union[str, "_models.ServiceKind"]] = None, + identity: Optional["_models.ManagedIdentity"] = None, + tls: Optional["_models.SignalRTlsSettings"] = None, + features: Optional[List["_models.SignalRFeature"]] = None, + live_trace_configuration: Optional["_models.LiveTraceConfiguration"] = None, + resource_log_configuration: Optional["_models.ResourceLogConfiguration"] = None, + cors: Optional["_models.SignalRCorsSettings"] = None, + serverless: Optional["_models.ServerlessSettings"] = None, + upstream: Optional["_models.ServerlessUpstreamSettings"] = None, + network_ac_ls: Optional["_models.SignalRNetworkACLs"] = None, + public_network_access: str = "Enabled", + disable_local_auth: bool = False, + disable_aad_auth: bool = False, **kwargs ): """ :keyword location: The GEO location of the resource. e.g. West US | East US | North Central US | South Central US. :paramtype location: str - :keyword tags: A set of tags. Tags of the service which is a list of key value pairs that - describe the resource. + :keyword tags: Tags of the service which is a list of key value pairs that describe the + resource. :paramtype tags: dict[str, str] :keyword sku: The billing information of the resource. :paramtype sku: ~azure.mgmt.signalr.models.ResourceSku - :keyword kind: The kind of the service, it can be SignalR or RawWebSockets. Possible values - include: "SignalR", "RawWebSockets". + :keyword kind: The kind of the service, it can be SignalR or RawWebSockets. Known values are: + "SignalR" and "RawWebSockets". :paramtype kind: str or ~azure.mgmt.signalr.models.ServiceKind :keyword identity: A class represent managed identities used for request and response. :paramtype identity: ~azure.mgmt.signalr.models.ManagedIdentity :keyword tls: TLS settings for the resource. :paramtype tls: ~azure.mgmt.signalr.models.SignalRTlsSettings :keyword features: List of the featureFlags. - + FeatureFlags that are not included in the parameters for the update operation will not be modified. And the response will only include featureFlags that are explicitly set. @@ -2210,6 +2146,8 @@ def __init__( :paramtype resource_log_configuration: ~azure.mgmt.signalr.models.ResourceLogConfiguration :keyword cors: Cross-Origin Resource Sharing (CORS) settings. :paramtype cors: ~azure.mgmt.signalr.models.SignalRCorsSettings + :keyword serverless: Serverless settings. + :paramtype serverless: ~azure.mgmt.signalr.models.ServerlessSettings :keyword upstream: The settings for the Upstream when the service is in server-less mode. :paramtype upstream: ~azure.mgmt.signalr.models.ServerlessUpstreamSettings :keyword network_ac_ls: Network ACLs for the resource. @@ -2228,7 +2166,7 @@ def __init__( When set as true, connection with AuthType=aad won't work. :paramtype disable_aad_auth: bool """ - super(SignalRResource, self).__init__(location=location, tags=tags, **kwargs) + super().__init__(location=location, tags=tags, **kwargs) self.sku = sku self.kind = kind self.identity = identity @@ -2247,6 +2185,7 @@ def __init__( self.live_trace_configuration = live_trace_configuration self.resource_log_configuration = resource_log_configuration self.cors = cors + self.serverless = serverless self.upstream = upstream self.network_ac_ls = network_ac_ls self.public_network_access = public_network_access @@ -2254,7 +2193,7 @@ def __init__( self.disable_aad_auth = disable_aad_auth -class SignalRResourceList(msrest.serialization.Model): +class SignalRResourceList(_serialization.Model): """Object that includes an array of resources and a possible link for next set. :ivar value: List of the resources. @@ -2265,16 +2204,12 @@ class SignalRResourceList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[SignalRResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[SignalRResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["SignalRResource"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.SignalRResource"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: List of the resources. @@ -2284,12 +2219,12 @@ def __init__( It's null for now, added for future use. :paramtype next_link: str """ - super(SignalRResourceList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class SignalRTlsSettings(msrest.serialization.Model): +class SignalRTlsSettings(_serialization.Model): """TLS settings for the resource. :ivar client_cert_enabled: Request client certificate during TLS handshake if enabled. @@ -2297,33 +2232,28 @@ class SignalRTlsSettings(msrest.serialization.Model): """ _attribute_map = { - 'client_cert_enabled': {'key': 'clientCertEnabled', 'type': 'bool'}, + "client_cert_enabled": {"key": "clientCertEnabled", "type": "bool"}, } - def __init__( - self, - *, - client_cert_enabled: Optional[bool] = True, - **kwargs - ): + def __init__(self, *, client_cert_enabled: bool = True, **kwargs): """ :keyword client_cert_enabled: Request client certificate during TLS handshake if enabled. :paramtype client_cert_enabled: bool """ - super(SignalRTlsSettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.client_cert_enabled = client_cert_enabled -class SignalRUsage(msrest.serialization.Model): +class SignalRUsage(_serialization.Model): """Object that describes a specific usage of the resources. :ivar id: Fully qualified ARM resource id. :vartype id: str :ivar current_value: Current value for the usage quota. - :vartype current_value: long + :vartype current_value: int :ivar limit: The maximum permitted value for the usage quota. If there is no limit, this value will be -1. - :vartype limit: long + :vartype limit: int :ivar name: Localizable String object containing the name and a localized value. :vartype name: ~azure.mgmt.signalr.models.SignalRUsageName :ivar unit: Representing the units of the usage quota. Possible values are: Count, Bytes, @@ -2332,20 +2262,20 @@ class SignalRUsage(msrest.serialization.Model): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'current_value': {'key': 'currentValue', 'type': 'long'}, - 'limit': {'key': 'limit', 'type': 'long'}, - 'name': {'key': 'name', 'type': 'SignalRUsageName'}, - 'unit': {'key': 'unit', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "current_value": {"key": "currentValue", "type": "int"}, + "limit": {"key": "limit", "type": "int"}, + "name": {"key": "name", "type": "SignalRUsageName"}, + "unit": {"key": "unit", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin current_value: Optional[int] = None, limit: Optional[int] = None, - name: Optional["SignalRUsageName"] = None, + name: Optional["_models.SignalRUsageName"] = None, unit: Optional[str] = None, **kwargs ): @@ -2353,17 +2283,17 @@ def __init__( :keyword id: Fully qualified ARM resource id. :paramtype id: str :keyword current_value: Current value for the usage quota. - :paramtype current_value: long + :paramtype current_value: int :keyword limit: The maximum permitted value for the usage quota. If there is no limit, this value will be -1. - :paramtype limit: long + :paramtype limit: int :keyword name: Localizable String object containing the name and a localized value. :paramtype name: ~azure.mgmt.signalr.models.SignalRUsageName :keyword unit: Representing the units of the usage quota. Possible values are: Count, Bytes, Seconds, Percent, CountPerSecond, BytesPerSecond. :paramtype unit: str """ - super(SignalRUsage, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.current_value = current_value self.limit = limit @@ -2371,7 +2301,7 @@ def __init__( self.unit = unit -class SignalRUsageList(msrest.serialization.Model): +class SignalRUsageList(_serialization.Model): """Object that includes an array of the resource usages and a possible link for next set. :ivar value: List of the resource usages. @@ -2382,16 +2312,12 @@ class SignalRUsageList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[SignalRUsage]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[SignalRUsage]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["SignalRUsage"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.SignalRUsage"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: List of the resource usages. @@ -2401,12 +2327,12 @@ def __init__( It's null for now, added for future use. :paramtype next_link: str """ - super(SignalRUsageList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class SignalRUsageName(msrest.serialization.Model): +class SignalRUsageName(_serialization.Model): """Localizable String object containing the name and a localized value. :ivar value: The identifier of the usage. @@ -2416,29 +2342,23 @@ class SignalRUsageName(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': 'str'}, - 'localized_value': {'key': 'localizedValue', 'type': 'str'}, + "value": {"key": "value", "type": "str"}, + "localized_value": {"key": "localizedValue", "type": "str"}, } - def __init__( - self, - *, - value: Optional[str] = None, - localized_value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[str] = None, localized_value: Optional[str] = None, **kwargs): """ :keyword value: The identifier of the usage. :paramtype value: str :keyword localized_value: Localized name of the usage. :paramtype localized_value: str """ - super(SignalRUsageName, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.localized_value = localized_value -class Sku(msrest.serialization.Model): +class Sku(_serialization.Model): """Describes an available sku.". Variables are only populated by the server, and will be ignored when sending a request. @@ -2452,30 +2372,26 @@ class Sku(msrest.serialization.Model): """ _validation = { - 'resource_type': {'readonly': True}, - 'sku': {'readonly': True}, - 'capacity': {'readonly': True}, + "resource_type": {"readonly": True}, + "sku": {"readonly": True}, + "capacity": {"readonly": True}, } _attribute_map = { - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'ResourceSku'}, - 'capacity': {'key': 'capacity', 'type': 'SkuCapacity'}, + "resource_type": {"key": "resourceType", "type": "str"}, + "sku": {"key": "sku", "type": "ResourceSku"}, + "capacity": {"key": "capacity", "type": "SkuCapacity"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Sku, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.resource_type = None self.sku = None self.capacity = None -class SkuCapacity(msrest.serialization.Model): +class SkuCapacity(_serialization.Model): """Describes scaling information of a sku. Variables are only populated by the server, and will be ignored when sending a request. @@ -2488,34 +2404,30 @@ class SkuCapacity(msrest.serialization.Model): :vartype default: int :ivar allowed_values: Allows capacity value list. :vartype allowed_values: list[int] - :ivar scale_type: The scale type applicable to the sku. Possible values include: "None", - "Manual", "Automatic". + :ivar scale_type: The scale type applicable to the sku. Known values are: "None", "Manual", and + "Automatic". :vartype scale_type: str or ~azure.mgmt.signalr.models.ScaleType """ _validation = { - 'minimum': {'readonly': True}, - 'maximum': {'readonly': True}, - 'default': {'readonly': True}, - 'allowed_values': {'readonly': True}, - 'scale_type': {'readonly': True}, + "minimum": {"readonly": True}, + "maximum": {"readonly": True}, + "default": {"readonly": True}, + "allowed_values": {"readonly": True}, + "scale_type": {"readonly": True}, } _attribute_map = { - 'minimum': {'key': 'minimum', 'type': 'int'}, - 'maximum': {'key': 'maximum', 'type': 'int'}, - 'default': {'key': 'default', 'type': 'int'}, - 'allowed_values': {'key': 'allowedValues', 'type': '[int]'}, - 'scale_type': {'key': 'scaleType', 'type': 'str'}, + "minimum": {"key": "minimum", "type": "int"}, + "maximum": {"key": "maximum", "type": "int"}, + "default": {"key": "default", "type": "int"}, + "allowed_values": {"key": "allowedValues", "type": "[int]"}, + "scale_type": {"key": "scaleType", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(SkuCapacity, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.minimum = None self.maximum = None self.default = None @@ -2523,7 +2435,7 @@ def __init__( self.scale_type = None -class SkuList(msrest.serialization.Model): +class SkuList(_serialization.Model): """The list skus operation response. Variables are only populated by the server, and will be ignored when sending a request. @@ -2536,82 +2448,78 @@ class SkuList(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Sku]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Sku]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(SkuList, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = 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. Possible values include: - "User", "Application", "ManagedIdentity", "Key". + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". :vartype created_by_type: str or ~azure.mgmt.signalr.models.CreatedByType :ivar created_at: The timestamp of resource creation (UTC). :vartype created_at: ~datetime.datetime :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str - :ivar last_modified_by_type: The type of identity that last modified the resource. Possible - values include: "User", "Application", "ManagedIdentity", "Key". + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". :vartype last_modified_by_type: str or ~azure.mgmt.signalr.models.CreatedByType :ivar last_modified_at: The timestamp of resource last modification (UTC). :vartype last_modified_at: ~datetime.datetime """ _attribute_map = { - 'created_by': {'key': 'createdBy', 'type': 'str'}, - 'created_by_type': {'key': 'createdByType', 'type': 'str'}, - 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, - 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, - 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, } def __init__( self, *, created_by: Optional[str] = None, - created_by_type: Optional[Union[str, "CreatedByType"]] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, - last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, **kwargs ): """ :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. Possible values - include: "User", "Application", "ManagedIdentity", "Key". + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". :paramtype created_by_type: str or ~azure.mgmt.signalr.models.CreatedByType :keyword created_at: The timestamp of resource creation (UTC). :paramtype created_at: ~datetime.datetime :keyword last_modified_by: The identity that last modified the resource. :paramtype last_modified_by: str - :keyword last_modified_by_type: The type of identity that last modified the resource. Possible - values include: "User", "Application", "ManagedIdentity", "Key". + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". :paramtype last_modified_by_type: str or ~azure.mgmt.signalr.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 @@ -2620,98 +2528,98 @@ def __init__( self.last_modified_at = last_modified_at -class UpstreamAuthSettings(msrest.serialization.Model): +class UpstreamAuthSettings(_serialization.Model): """Upstream auth settings. If not set, no auth is used for upstream messages. - :ivar type: Upstream auth type enum. Possible values include: "None", "ManagedIdentity". + :ivar type: Upstream auth type enum. Known values are: "None" and "ManagedIdentity". :vartype type: str or ~azure.mgmt.signalr.models.UpstreamAuthType :ivar managed_identity: Managed identity settings for upstream. :vartype managed_identity: ~azure.mgmt.signalr.models.ManagedIdentitySettings """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'managed_identity': {'key': 'managedIdentity', 'type': 'ManagedIdentitySettings'}, + "type": {"key": "type", "type": "str"}, + "managed_identity": {"key": "managedIdentity", "type": "ManagedIdentitySettings"}, } def __init__( self, *, - type: Optional[Union[str, "UpstreamAuthType"]] = None, - managed_identity: Optional["ManagedIdentitySettings"] = None, + type: Optional[Union[str, "_models.UpstreamAuthType"]] = None, + managed_identity: Optional["_models.ManagedIdentitySettings"] = None, **kwargs ): """ - :keyword type: Upstream auth type enum. Possible values include: "None", "ManagedIdentity". + :keyword type: Upstream auth type enum. Known values are: "None" and "ManagedIdentity". :paramtype type: str or ~azure.mgmt.signalr.models.UpstreamAuthType :keyword managed_identity: Managed identity settings for upstream. :paramtype managed_identity: ~azure.mgmt.signalr.models.ManagedIdentitySettings """ - super(UpstreamAuthSettings, self).__init__(**kwargs) + super().__init__(**kwargs) self.type = type self.managed_identity = managed_identity -class UpstreamTemplate(msrest.serialization.Model): +class UpstreamTemplate(_serialization.Model): """Upstream template item settings. It defines the Upstream URL of the incoming requests. -The template defines the pattern of the event, the hub or the category of the incoming request that matches current URL template. + The template defines the pattern of the event, the hub or the category of the incoming request that matches current URL template. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to Azure. + + :ivar hub_pattern: Gets or sets the matching pattern for hub names. If not set, it matches any + hub. + There are 3 kind of patterns supported: - :ivar hub_pattern: Gets or sets the matching pattern for hub names. If not set, it matches any - hub. - There are 3 kind of patterns supported: - - .. code-block:: - - 1. "*", it to matches any hub name. - 2. Combine multiple hubs with ",", for example "hub1,hub2", it matches "hub1" and "hub2". - 3. The single hub name, for example, "hub1", it matches "hub1". - :vartype hub_pattern: str - :ivar event_pattern: Gets or sets the matching pattern for event names. If not set, it matches - any event. - There are 3 kind of patterns supported: - - .. code-block:: - - 1. "*", it to matches any event name. - 2. Combine multiple events with ",", for example "connect,disconnect", it matches event - "connect" and "disconnect". - 3. The single event name, for example, "connect", it matches "connect". - :vartype event_pattern: str - :ivar category_pattern: Gets or sets the matching pattern for category names. If not set, it - matches any category. - There are 3 kind of patterns supported: - - .. code-block:: - - 1. "*", it to matches any category name. - 2. Combine multiple categories with ",", for example "connections,messages", it matches - category "connections" and "messages". - 3. The single category name, for example, "connections", it matches the category - "connections". - :vartype category_pattern: str - :ivar url_template: Required. Gets or sets the Upstream URL template. You can use 3 predefined - parameters {hub}, {category} {event} inside the template, the value of the Upstream URL is - dynamically calculated when the client request comes in. - For example, if the urlTemplate is ``http://example.com/{hub}/api/{event}``\ , with a client - request from hub ``chat`` connects, it will first POST to this URL: - ``http://example.com/chat/api/connect``. - :vartype url_template: str - :ivar auth: Upstream auth settings. If not set, no auth is used for upstream messages. - :vartype auth: ~azure.mgmt.signalr.models.UpstreamAuthSettings + .. code-block:: + + 1. "*", it to matches any hub name. + 2. Combine multiple hubs with ",", for example "hub1,hub2", it matches "hub1" and "hub2". + 3. The single hub name, for example, "hub1", it matches "hub1". + :vartype hub_pattern: str + :ivar event_pattern: Gets or sets the matching pattern for event names. If not set, it matches + any event. + There are 3 kind of patterns supported: + + .. code-block:: + + 1. "*", it to matches any event name. + 2. Combine multiple events with ",", for example "connect,disconnect", it matches event + "connect" and "disconnect". + 3. The single event name, for example, "connect", it matches "connect". + :vartype event_pattern: str + :ivar category_pattern: Gets or sets the matching pattern for category names. If not set, it + matches any category. + There are 3 kind of patterns supported: + + .. code-block:: + + 1. "*", it to matches any category name. + 2. Combine multiple categories with ",", for example "connections,messages", it matches + category "connections" and "messages". + 3. The single category name, for example, "connections", it matches the category + "connections". + :vartype category_pattern: str + :ivar url_template: Gets or sets the Upstream URL template. You can use 3 predefined parameters + {hub}, {category} {event} inside the template, the value of the Upstream URL is dynamically + calculated when the client request comes in. + For example, if the urlTemplate is ``http://example.com/{hub}/api/{event}``\ , with a client + request from hub ``chat`` connects, it will first POST to this URL: + ``http://example.com/chat/api/connect``. Required. + :vartype url_template: str + :ivar auth: Upstream auth settings. If not set, no auth is used for upstream messages. + :vartype auth: ~azure.mgmt.signalr.models.UpstreamAuthSettings """ _validation = { - 'url_template': {'required': True}, + "url_template": {"required": True}, } _attribute_map = { - 'hub_pattern': {'key': 'hubPattern', 'type': 'str'}, - 'event_pattern': {'key': 'eventPattern', 'type': 'str'}, - 'category_pattern': {'key': 'categoryPattern', 'type': 'str'}, - 'url_template': {'key': 'urlTemplate', 'type': 'str'}, - 'auth': {'key': 'auth', 'type': 'UpstreamAuthSettings'}, + "hub_pattern": {"key": "hubPattern", "type": "str"}, + "event_pattern": {"key": "eventPattern", "type": "str"}, + "category_pattern": {"key": "categoryPattern", "type": "str"}, + "url_template": {"key": "urlTemplate", "type": "str"}, + "auth": {"key": "auth", "type": "UpstreamAuthSettings"}, } def __init__( @@ -2721,16 +2629,16 @@ def __init__( hub_pattern: Optional[str] = None, event_pattern: Optional[str] = None, category_pattern: Optional[str] = None, - auth: Optional["UpstreamAuthSettings"] = None, + auth: Optional["_models.UpstreamAuthSettings"] = None, **kwargs ): """ :keyword hub_pattern: Gets or sets the matching pattern for hub names. If not set, it matches any hub. There are 3 kind of patterns supported: - + .. code-block:: - + 1. "*", it to matches any hub name. 2. Combine multiple hubs with ",", for example "hub1,hub2", it matches "hub1" and "hub2". 3. The single hub name, for example, "hub1", it matches "hub1". @@ -2738,9 +2646,9 @@ def __init__( :keyword event_pattern: Gets or sets the matching pattern for event names. If not set, it matches any event. There are 3 kind of patterns supported: - + .. code-block:: - + 1. "*", it to matches any event name. 2. Combine multiple events with ",", for example "connect,disconnect", it matches event "connect" and "disconnect". @@ -2749,26 +2657,26 @@ def __init__( :keyword category_pattern: Gets or sets the matching pattern for category names. If not set, it matches any category. There are 3 kind of patterns supported: - + .. code-block:: - + 1. "*", it to matches any category name. 2. Combine multiple categories with ",", for example "connections,messages", it matches category "connections" and "messages". 3. The single category name, for example, "connections", it matches the category "connections". :paramtype category_pattern: str - :keyword url_template: Required. Gets or sets the Upstream URL template. You can use 3 - predefined parameters {hub}, {category} {event} inside the template, the value of the Upstream - URL is dynamically calculated when the client request comes in. + :keyword url_template: Gets or sets the Upstream URL template. You can use 3 predefined + parameters {hub}, {category} {event} inside the template, the value of the Upstream URL is + dynamically calculated when the client request comes in. For example, if the urlTemplate is ``http://example.com/{hub}/api/{event}``\ , with a client request from hub ``chat`` connects, it will first POST to this URL: - ``http://example.com/chat/api/connect``. + ``http://example.com/chat/api/connect``. Required. :paramtype url_template: str :keyword auth: Upstream auth settings. If not set, no auth is used for upstream messages. :paramtype auth: ~azure.mgmt.signalr.models.UpstreamAuthSettings """ - super(UpstreamTemplate, self).__init__(**kwargs) + super().__init__(**kwargs) self.hub_pattern = hub_pattern self.event_pattern = event_pattern self.category_pattern = category_pattern @@ -2776,7 +2684,7 @@ def __init__( self.auth = auth -class UserAssignedIdentityProperty(msrest.serialization.Model): +class UserAssignedIdentityProperty(_serialization.Model): """Properties of user assigned identity. Variables are only populated by the server, and will be ignored when sending a request. @@ -2788,21 +2696,17 @@ class UserAssignedIdentityProperty(msrest.serialization.Model): """ _validation = { - 'principal_id': {'readonly': True}, - 'client_id': {'readonly': True}, + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, } _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'client_id': {'key': 'clientId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(UserAssignedIdentityProperty, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.principal_id = None self.client_id = None diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_patch.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_signal_rmanagement_client_enums.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_signal_rmanagement_client_enums.py index cf7aa123655a..08ca30eb6629 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_signal_rmanagement_client_enums.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/models/_signal_rmanagement_client_enums.py @@ -7,30 +7,29 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class ACLAction(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Azure Networking ACL Action. - """ +class ACLAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Azure Networking ACL Action.""" ALLOW = "Allow" DENY = "Deny" -class CreatedByType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of identity that created the resource. - """ + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key" -class FeatureFlags(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class FeatureFlags(str, Enum, metaclass=CaseInsensitiveEnumMeta): """FeatureFlags is the supported features of Azure SignalR service. - - + + * ServiceMode: Flag for backend server for SignalR service. Values allowed: "Default": have your own backend server; "Serverless": your application doesn't have a backend server; "Classic": for backward compatibility. Support both Default and Serverless mode but not @@ -51,23 +50,24 @@ class FeatureFlags(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): ENABLE_MESSAGING_LOGS = "EnableMessagingLogs" ENABLE_LIVE_TRACE = "EnableLiveTrace" -class KeyType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of access key. - """ + +class KeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of access key.""" PRIMARY = "Primary" SECONDARY = "Secondary" SALT = "Salt" -class ManagedIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Represents the identity type: systemAssigned, userAssigned, None - """ + +class ManagedIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Represents the identity type: systemAssigned, userAssigned, None.""" NONE = "None" SYSTEM_ASSIGNED = "SystemAssigned" USER_ASSIGNED = "UserAssigned" -class PrivateLinkServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. """ @@ -77,9 +77,9 @@ class PrivateLinkServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, REJECTED = "Rejected" DISCONNECTED = "Disconnected" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Provisioning state of the resource. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Provisioning state of the resource.""" UNKNOWN = "Unknown" SUCCEEDED = "Succeeded" @@ -91,24 +91,24 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): DELETING = "Deleting" MOVING = "Moving" -class ScaleType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The scale type applicable to the sku. - """ + +class ScaleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The scale type applicable to the sku.""" NONE = "None" MANUAL = "Manual" AUTOMATIC = "Automatic" -class ServiceKind(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The kind of the service, it can be SignalR or RawWebSockets - """ + +class ServiceKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of the service, it can be SignalR or RawWebSockets.""" SIGNAL_R = "SignalR" RAW_WEB_SOCKETS = "RawWebSockets" -class SharedPrivateLinkResourceStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Status of the shared private link resource - """ + +class SharedPrivateLinkResourceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the shared private link resource.""" PENDING = "Pending" APPROVED = "Approved" @@ -116,18 +116,19 @@ class SharedPrivateLinkResourceStatus(with_metaclass(CaseInsensitiveEnumMeta, st DISCONNECTED = "Disconnected" TIMEOUT = "Timeout" -class SignalRRequestType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The incoming request type to the service - """ + +class SignalRRequestType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The incoming request type to the service.""" CLIENT_CONNECTION = "ClientConnection" SERVER_CONNECTION = "ServerConnection" RESTAPI = "RESTAPI" TRACE = "Trace" -class SignalRSkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class SignalRSkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Optional tier of this particular SKU. 'Standard' or 'Free'. - + ``Basic`` is deprecated, use ``Standard`` instead. """ @@ -136,9 +137,9 @@ class SignalRSkuTier(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): STANDARD = "Standard" PREMIUM = "Premium" -class UpstreamAuthType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Upstream auth type enum. - """ + +class UpstreamAuthType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Upstream auth type enum.""" NONE = "None" MANAGED_IDENTITY = "ManagedIdentity" diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/__init__.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/__init__.py index bab1a78daafd..0fe4134b4d88 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/__init__.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/__init__.py @@ -15,13 +15,19 @@ from ._signal_rprivate_link_resources_operations import SignalRPrivateLinkResourcesOperations from ._signal_rshared_private_link_resources_operations import SignalRSharedPrivateLinkResourcesOperations +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__ = [ - 'Operations', - 'SignalROperations', - 'UsagesOperations', - 'SignalRCustomCertificatesOperations', - 'SignalRCustomDomainsOperations', - 'SignalRPrivateEndpointConnectionsOperations', - 'SignalRPrivateLinkResourcesOperations', - 'SignalRSharedPrivateLinkResourcesOperations', + "Operations", + "SignalROperations", + "UsagesOperations", + "SignalRCustomCertificatesOperations", + "SignalRCustomDomainsOperations", + "SignalRPrivateEndpointConnectionsOperations", + "SignalRPrivateLinkResourcesOperations", + "SignalRSharedPrivateLinkResourcesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_operations.py index fb83747d245f..90e7fb0879a7 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,106 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/providers/Microsoft.SignalRService/operations') + _url = kwargs.pop("template_url", "/providers/Microsoft.SignalRService/operations") # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class Operations(object): - """Operations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.OperationList"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available REST API operations of the Microsoft.SignalRService provider. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.OperationList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -118,7 +137,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -128,8 +149,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.SignalRService/operations'} # type: ignore + list.metadata = {"url": "/providers/Microsoft.SignalRService/operations"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_patch.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_r_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_r_operations.py index 954d0a4f8fca..b7d70bf5efe9 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_r_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_r_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,503 +6,498 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_check_name_availability_request( - location: str, - subscription_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] - api_version = "2022-02-01" - accept = "application/json" +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/checkNameAvailability') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/checkNameAvailability", + ) # pylint: disable=line-too-long path_format_arguments = { - "location": _SERIALIZER.url("location", location, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "location": _SERIALIZER.url("location", location, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_list_by_subscription_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_subscription_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/signalR') + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/signalR") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - *, - json: JSONType = 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, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2022-02-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - resource_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, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2022-02-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PATCH", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_keys_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/listKeys') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/listKeys", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_regenerate_key_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_regenerate_key_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2022-02-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_restart_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_restart_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_list_skus_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/skus') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/skus", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SignalROperations(object): - """SignalROperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class SignalROperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`signal_r` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace + @overload def check_name_availability( self, location: str, - parameters: "_models.NameAvailabilityParameters", + parameters: _models.NameAvailabilityParameters, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.NameAvailability": + ) -> _models.NameAvailability: """Checks that the resource name is valid and is not already in use. - :param location: the region. + :param location: the region. Required. :type location: str - :param parameters: Parameters supplied to the operation. + :param parameters: Parameters supplied to the operation. Required. :type parameters: ~azure.mgmt.signalr.models.NameAvailabilityParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default 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.signalr.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, location: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.NameAvailability: + """Checks that the resource name is valid and is not already in use. + + :param location: the region. Required. + :type location: str + :param parameters: Parameters supplied to the 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 + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.signalr.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, parameters: Union[_models.NameAvailabilityParameters, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Checks that the resource name is valid and is not already in use. + + :param location: the region. Required. + :type location: str + :param parameters: Parameters supplied to the operation. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.signalr.models.NameAvailabilityParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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.signalr.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.NameAvailability"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'NameAvailabilityParameters') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "NameAvailabilityParameters") request = build_check_name_availability_request( location=location, subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -509,51 +505,66 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/checkNameAvailability'} # type: ignore - + check_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/checkNameAvailability"} # type: ignore @distributed_trace - def list_by_subscription( - self, - **kwargs: Any - ) -> Iterable["_models.SignalRResourceList"]: + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.SignalRResource"]: """Handles requests to list all resources in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SignalRResourceList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SignalRResourceList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SignalRResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, - template_url=self.list_by_subscription.metadata['url'], + api_version=api_version, + template_url=self.list_by_subscription.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -567,7 +578,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -577,53 +590,65 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/signalR'} # type: ignore + list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/signalR"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.SignalRResourceList"]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.SignalRResource"]: """Handles requests to list all resources in a resource group. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. 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 SignalRResourceList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SignalRResourceList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SignalRResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, - template_url=self.list_by_resource_group.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -637,7 +662,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -647,48 +674,54 @@ 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.SignalRService/signalR'} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SignalRResource": + def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.SignalRResource: """Get the resource and its properties. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SignalRResource, or the result of cls(response) + :return: SignalRResource or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SignalRResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResource] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -696,83 +729,178 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> Optional["_models.SignalRResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.SignalRResource"]] + ) -> Optional[_models.SignalRResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'SignalRResource') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.SignalRResource]] - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "SignalRResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(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('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + parameters: _models.SignalRResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SignalRResource]: + """Create or update a resource. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the create or update operation. Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SignalRResource]: + """Create or update a resource. + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the create or update 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> LROPoller["_models.SignalRResource"]: + ) -> LROPoller[_models.SignalRResource]: """Create or update a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: Parameters for the create or update operation. - :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :param parameters: Parameters for the create or update operation. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -784,98 +912,107 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either SignalRResource or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResource] + 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( + raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore - def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore @distributed_trace - def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> LROPoller[None]: """Operation to delete a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -887,108 +1024,211 @@ def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore def _update_initial( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> Optional["_models.SignalRResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.SignalRResource"]] + ) -> Optional[_models.SignalRResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'SignalRResource') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.SignalRResource]] - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "SignalRResource") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(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 if response.status_code == 200: - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + parameters: _models.SignalRResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SignalRResource]: + """Operation to update an exiting resource. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the update operation. Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SignalRResource]: + """Operation to update an exiting resource. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameters for the update 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 SignalRResource or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_update( self, resource_group_name: str, resource_name: str, - parameters: "_models.SignalRResource", + parameters: Union[_models.SignalRResource, IO], **kwargs: Any - ) -> LROPoller["_models.SignalRResource"]: + ) -> LROPoller[_models.SignalRResource]: """Operation to update an exiting resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: Parameters for the update operation. - :type parameters: ~azure.mgmt.signalr.models.SignalRResource + :param parameters: Parameters for the update operation. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.signalr.models.SignalRResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -1000,86 +1240,98 @@ def begin_update( :return: An instance of LROPoller that returns either SignalRResource or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRResource] + 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( + raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SignalRResource', pipeline_response) + deserialized = self._deserialize("SignalRResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}'} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}"} # type: ignore @distributed_trace - def list_keys( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SignalRKeys": + def list_keys(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.SignalRKeys: """Get the access keys of the resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SignalRKeys, or the result of cls(response) + :return: SignalRKeys or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SignalRKeys - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRKeys"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRKeys] - request = build_list_keys_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list_keys.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_keys.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -1087,79 +1339,176 @@ def list_keys( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SignalRKeys', pipeline_response) + deserialized = self._deserialize("SignalRKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/listKeys'} # type: ignore - + list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/listKeys"} # type: ignore def _regenerate_key_initial( self, resource_group_name: str, resource_name: str, - parameters: "_models.RegenerateKeyParameters", + parameters: Union[_models.RegenerateKeyParameters, IO], **kwargs: Any - ) -> "_models.SignalRKeys": - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRKeys"] + ) -> _models.SignalRKeys: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'RegenerateKeyParameters') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRKeys] - request = build_regenerate_key_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RegenerateKeyParameters") + + request = build_regenerate_key_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._regenerate_key_initial.metadata['url'], + content=_content, + template_url=self._regenerate_key_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [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 = self._deserialize('SignalRKeys', pipeline_response) + deserialized = self._deserialize("SignalRKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _regenerate_key_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey'} # type: ignore + _regenerate_key_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey"} # type: ignore + + @overload + def begin_regenerate_key( + self, + resource_group_name: str, + resource_name: str, + parameters: _models.RegenerateKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SignalRKeys]: + """Regenerate the access key for the resource. PrimaryKey and SecondaryKey cannot be regenerated + at the same time. + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameter that describes the Regenerate Key Operation. Required. + :type parameters: ~azure.mgmt.signalr.models.RegenerateKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 SignalRKeys or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRKeys] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_regenerate_key( + self, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SignalRKeys]: + """Regenerate the access key for the resource. PrimaryKey and SecondaryKey cannot be regenerated + at the same time. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: Parameter that describes the Regenerate Key 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 SignalRKeys or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRKeys] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_regenerate_key( self, resource_group_name: str, resource_name: str, - parameters: "_models.RegenerateKeyParameters", + parameters: Union[_models.RegenerateKeyParameters, IO], **kwargs: Any - ) -> LROPoller["_models.SignalRKeys"]: + ) -> LROPoller[_models.SignalRKeys]: """Regenerate the access key for the resource. PrimaryKey and SecondaryKey cannot be regenerated at the same time. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: Parameter that describes the Regenerate Key Operation. - :type parameters: ~azure.mgmt.signalr.models.RegenerateKeyParameters + :param parameters: Parameter that describes the Regenerate Key Operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.RegenerateKeyParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -1171,98 +1520,109 @@ def begin_regenerate_key( :return: An instance of LROPoller that returns either SignalRKeys or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SignalRKeys] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRKeys"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRKeys] + 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._regenerate_key_initial( + raw_result = self._regenerate_key_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SignalRKeys', pipeline_response) + deserialized = self._deserialize("SignalRKeys", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_regenerate_key.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey'} # type: ignore + begin_regenerate_key.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/regenerateKey"} # type: ignore - def _restart_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any + def _restart_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_restart_request( resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._restart_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._restart_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [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, {}) - _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart'} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart"} # type: ignore @distributed_trace - def begin_restart( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_restart(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> LROPoller[None]: """Operation to restart a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -1274,80 +1634,95 @@ def begin_restart( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._restart_initial( + raw_result = self._restart_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + 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 + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart'} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/restart"} # type: ignore @distributed_trace - def list_skus( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SkuList": + def list_skus(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.SkuList: """List all available skus of the resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SkuList, or the result of cls(response) + :return: SkuList or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SkuList - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SkuList"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SkuList] - request = build_list_skus_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list_skus.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_skus.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -1355,12 +1730,11 @@ def list_skus( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SkuList', pipeline_response) + deserialized = self._deserialize("SkuList", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_skus.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/skus'} # type: ignore - + list_skus.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/skus"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_certificates_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_certificates_operations.py index 77ae54badc28..5bbec0148ed2 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_certificates_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_certificates_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,253 +6,247 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - certificate_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), - "certificateName": _SERIALIZER.url("certificate_name", certificate_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "certificateName": _SERIALIZER.url("certificate_name", certificate_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - certificate_name: str, - *, - json: JSONType = 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, resource_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2022-02-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), - "certificateName": _SERIALIZER.url("certificate_name", certificate_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "certificateName": _SERIALIZER.url("certificate_name", certificate_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_delete_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - certificate_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, certificate_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), - "certificateName": _SERIALIZER.url("certificate_name", certificate_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "certificateName": _SERIALIZER.url("certificate_name", certificate_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SignalRCustomCertificatesOperations(object): - """SignalRCustomCertificatesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class SignalRCustomCertificatesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`signal_rcustom_certificates` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Iterable["_models.CustomCertificateList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.CustomCertificate"]: """List all custom certificates. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomCertificateList or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.CustomCertificateList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CustomCertificate or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.CustomCertificate] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificateList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificateList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -265,7 +260,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -275,52 +272,59 @@ 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.SignalRService/signalR/{resourceName}/customCertificates'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - certificate_name: str, - **kwargs: Any - ) -> "_models.CustomCertificate": + self, resource_group_name: str, resource_name: str, certificate_name: str, **kwargs: Any + ) -> _models.CustomCertificate: """Get a custom certificate. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param certificate_name: Custom certificate name. + :param certificate_name: Custom certificate name. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomCertificate, or the result of cls(response) + :return: CustomCertificate or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.CustomCertificate - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificate"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificate] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -328,66 +332,163 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, resource_name: str, certificate_name: str, - parameters: "_models.CustomCertificate", + parameters: Union[_models.CustomCertificate, IO], **kwargs: Any - ) -> "_models.CustomCertificate": - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificate"] + ) -> _models.CustomCertificate: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CustomCertificate') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificate] - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CustomCertificate") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + certificate_name: str, + parameters: _models.CustomCertificate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CustomCertificate]: + """Create or update a custom certificate. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param certificate_name: Custom certificate name. Required. + :type certificate_name: str + :param parameters: Required. + :type parameters: ~azure.mgmt.signalr.models.CustomCertificate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 CustomCertificate or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.CustomCertificate] + :raises ~azure.core.exceptions.HttpResponseError: + """ + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + certificate_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CustomCertificate]: + """Create or update a custom certificate. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param certificate_name: Custom certificate name. Required. + :type certificate_name: str + :param parameters: Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 CustomCertificate or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.CustomCertificate] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -395,20 +496,23 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, certificate_name: str, - parameters: "_models.CustomCertificate", + parameters: Union[_models.CustomCertificate, IO], **kwargs: Any - ) -> LROPoller["_models.CustomCertificate"]: + ) -> LROPoller[_models.CustomCertificate]: """Create or update a custom certificate. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param certificate_name: Custom certificate name. + :param certificate_name: Custom certificate name. Required. :type certificate_name: str - :param parameters: - :type parameters: ~azure.mgmt.signalr.models.CustomCertificate + :param parameters: Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.CustomCertificate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/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 @@ -420,91 +524,104 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either CustomCertificate or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.CustomCertificate] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomCertificate"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomCertificate] + 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( + raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('CustomCertificate', pipeline_response) + deserialized = self._deserialize("CustomCertificate", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore @distributed_trace - def delete( - self, - resource_group_name: str, - resource_name: str, - certificate_name: str, - **kwargs: Any + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, certificate_name: str, **kwargs: Any ) -> None: """Delete a custom certificate. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param certificate_name: Custom certificate name. + :param certificate_name: Custom certificate name. Required. :type certificate_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - request = build_delete_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, certificate_name=certificate_name, - template_url=self.delete.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -515,5 +632,4 @@ def delete( if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}'} # type: ignore - + delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customCertificates/{certificateName}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_domains_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_domains_operations.py index 2e112e899d37..8fc580e2e76a 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_domains_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rcustom_domains_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,252 +6,245 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), - "name": _SERIALIZER.url("name", name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - name: str, - *, - json: JSONType = 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, resource_name: str, name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2022-02-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), - "name": _SERIALIZER.url("name", name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - 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, resource_name: str, name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), - "name": _SERIALIZER.url("name", name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SignalRCustomDomainsOperations(object): - """SignalRCustomDomainsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class SignalRCustomDomainsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`signal_rcustom_domains` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Iterable["_models.CustomDomainList"]: + def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> Iterable["_models.CustomDomain"]: """List all custom domains. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomDomainList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.CustomDomainList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CustomDomain or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.CustomDomain] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomainList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomainList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -264,7 +258,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -274,52 +270,57 @@ 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.SignalRService/signalR/{resourceName}/customDomains'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - resource_name: str, - name: str, - **kwargs: Any - ) -> "_models.CustomDomain": + def get(self, resource_group_name: str, resource_name: str, name: str, **kwargs: Any) -> _models.CustomDomain: """Get a custom domain. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param name: Custom domain name. + :param name: Custom domain name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomDomain, or the result of cls(response) + :return: CustomDomain or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.CustomDomain - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomain"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, name=name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -327,62 +328,159 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomDomain', pipeline_response) + deserialized = self._deserialize("CustomDomain", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, resource_name: str, name: str, - parameters: "_models.CustomDomain", + parameters: Union[_models.CustomDomain, IO], **kwargs: Any - ) -> "_models.CustomDomain": - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomain"] + ) -> _models.CustomDomain: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'CustomDomain') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain] - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CustomDomain") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, name=name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomDomain', pipeline_response) + deserialized = self._deserialize("CustomDomain", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + name: str, + parameters: _models.CustomDomain, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CustomDomain]: + """Create or update a custom domain. + + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param name: Custom domain name. Required. + :type name: str + :param parameters: Required. + :type parameters: ~azure.mgmt.signalr.models.CustomDomain + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 CustomDomain or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.CustomDomain] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CustomDomain]: + """Create or update a custom domain. + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param name: Custom domain name. Required. + :type name: str + :param parameters: Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Known values are: 'application/json', 'text/json'. Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 CustomDomain or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.CustomDomain] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -390,20 +488,23 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, name: str, - parameters: "_models.CustomDomain", + parameters: Union[_models.CustomDomain, IO], **kwargs: Any - ) -> LROPoller["_models.CustomDomain"]: + ) -> LROPoller[_models.CustomDomain]: """Create or update a custom domain. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param name: Custom domain name. + :param name: Custom domain name. Required. :type name: str - :param parameters: - :type parameters: ~azure.mgmt.signalr.models.CustomDomain + :param parameters: Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.CustomDomain or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json', + 'text/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 @@ -415,104 +516,111 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either CustomDomain or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.CustomDomain] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomDomain"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomDomain] + 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( + raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, name=name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('CustomDomain', pipeline_response) + deserialized = self._deserialize("CustomDomain", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore - def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, name=name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore @distributed_trace - def begin_delete( - self, - resource_group_name: str, - resource_name: str, - name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, resource_name: str, name: str, **kwargs: Any) -> LROPoller[None]: """Delete a custom domain. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param name: Custom domain name. + :param name: Custom domain name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -524,41 +632,48 @@ def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, name=name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/customDomains/{name}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_endpoint_connections_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_endpoint_connections_operations.py index c166e468a954..4d5b0cff707e 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_endpoint_connections_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_endpoint_connections_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,253 +6,266 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( private_endpoint_connection_name: str, - subscription_id: str, resource_group_name: str, resource_name: str, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_update_request( private_endpoint_connection_name: str, - subscription_id: str, resource_group_name: str, resource_name: str, - *, - json: JSONType = None, - content: Any = None, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2022-02-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - 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( private_endpoint_connection_name: str, - subscription_id: str, resource_group_name: str, resource_name: str, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SignalRPrivateEndpointConnectionsOperations(object): - """SignalRPrivateEndpointConnectionsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class SignalRPrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`signal_rprivate_endpoint_connections` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Iterable["_models.PrivateEndpointConnectionList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateEndpointConnection"]: """List private endpoint connections. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateEndpointConnectionList or the result of + :return: An iterator like instance of either PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.PrivateEndpointConnectionList] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnectionList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -265,7 +279,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -275,52 +291,59 @@ 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.SignalRService/signalR/{resourceName}/privateEndpointConnections'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections"} # type: ignore @distributed_trace def get( - self, - private_endpoint_connection_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get the specified private endpoint connection. - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - request = build_get_request( private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -328,15 +351,76 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + + @overload + def update( + self, + private_endpoint_connection_name: str, + resource_group_name: str, + resource_name: str, + parameters: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Update the state of specified private endpoint connection. + + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The resource of private endpoint and its properties. Required. + :type parameters: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + @overload + def update( + self, + private_endpoint_connection_name: str, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Update the state of specified private endpoint connection. + + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The resource of private endpoint and its properties. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def update( @@ -344,48 +428,72 @@ def update( private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, - parameters: "_models.PrivateEndpointConnection", + parameters: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + ) -> _models.PrivateEndpointConnection: """Update the state of specified private endpoint connection. - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: The resource of private endpoint and its properties. - :type parameters: ~azure.mgmt.signalr.models.PrivateEndpointConnection + :param parameters: The resource of private endpoint and its properties. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.signalr.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.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_update_request( private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self.update.metadata['url'], + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -393,69 +501,73 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore - + update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - def _delete_initial( - self, - private_endpoint_connection_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace def begin_delete( - self, - private_endpoint_connection_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + self, private_endpoint_connection_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> LROPoller[None]: """Delete the specified private endpoint connection. - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -467,41 +579,48 @@ def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore private_endpoint_connection_name=private_endpoint_connection_name, resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_link_resources_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_link_resources_operations.py index 862b2d70c199..ce2574f1d544 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_link_resources_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rprivate_link_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,130 +6,146 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateLinkResources') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateLinkResources", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SignalRPrivateLinkResourcesOperations(object): - """SignalRPrivateLinkResourcesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class SignalRPrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`signal_rprivate_link_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Iterable["_models.PrivateLinkResourceList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateLinkResource"]: """Get the private link resources that need to be created for a resource. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateLinkResourceList or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.PrivateLinkResourceList] - :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.signalr.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -142,7 +159,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -152,8 +171,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.SignalRService/signalR/{resourceName}/privateLinkResources'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/privateLinkResources"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rshared_private_link_resources_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rshared_private_link_resources_operations.py index f5cacae3efa7..3f91bed786b7 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rshared_private_link_resources_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_signal_rshared_private_link_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,253 +6,266 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse 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 msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( shared_private_link_resource_name: str, - subscription_id: str, resource_group_name: str, resource_name: str, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "sharedPrivateLinkResourceName": _SERIALIZER.url("shared_private_link_resource_name", shared_private_link_resource_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "sharedPrivateLinkResourceName": _SERIALIZER.url( + "shared_private_link_resource_name", shared_private_link_resource_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **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( shared_private_link_resource_name: str, - subscription_id: str, resource_group_name: str, resource_name: str, - *, - json: JSONType = None, - content: Any = None, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - api_version = "2022-02-01" - accept = "application/json" # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "sharedPrivateLinkResourceName": _SERIALIZER.url("shared_private_link_resource_name", shared_private_link_resource_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "sharedPrivateLinkResourceName": _SERIALIZER.url( + "shared_private_link_resource_name", shared_private_link_resource_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - 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( shared_private_link_resource_name: str, - subscription_id: str, resource_group_name: str, resource_name: str, + subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + _headers = case_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-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}') + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "sharedPrivateLinkResourceName": _SERIALIZER.url("shared_private_link_resource_name", shared_private_link_resource_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "sharedPrivateLinkResourceName": _SERIALIZER.url( + "shared_private_link_resource_name", shared_private_link_resource_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class SignalRSharedPrivateLinkResourcesOperations(object): - """SignalRSharedPrivateLinkResourcesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class SignalRSharedPrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`signal_rshared_private_link_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Iterable["_models.SharedPrivateLinkResourceList"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.SharedPrivateLinkResource"]: """List shared private link resources. :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SharedPrivateLinkResourceList or the result of + :return: An iterator like instance of either SharedPrivateLinkResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SharedPrivateLinkResourceList] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SharedPrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResourceList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResourceList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.list.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -265,7 +279,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -275,52 +291,60 @@ 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.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources"} # type: ignore @distributed_trace def get( - self, - shared_private_link_resource_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.SharedPrivateLinkResource": + self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.SharedPrivateLinkResource: """Get the specified shared private link resource. :param shared_private_link_resource_name: The name of the shared private link resource. + Required. :type shared_private_link_resource_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SharedPrivateLinkResource, or the result of cls(response) + :return: SharedPrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.signalr.models.SharedPrivateLinkResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResource] - request = build_get_request( shared_private_link_resource_name=shared_private_link_resource_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self.get.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: @@ -328,66 +352,165 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore def _create_or_update_initial( self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, - parameters: "_models.SharedPrivateLinkResource", + parameters: Union[_models.SharedPrivateLinkResource, IO], **kwargs: Any - ) -> "_models.SharedPrivateLinkResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResource"] + ) -> _models.SharedPrivateLinkResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(parameters, 'SharedPrivateLinkResource') + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResource] - request = build_create_or_update_request_initial( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "SharedPrivateLinkResource") + + request = build_create_or_update_request( shared_private_link_resource_name=shared_private_link_resource_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + 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 + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore + + @overload + def begin_create_or_update( + self, + shared_private_link_resource_name: str, + resource_group_name: str, + resource_name: str, + parameters: _models.SharedPrivateLinkResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SharedPrivateLinkResource]: + """Create or update a shared private link resource. + + :param shared_private_link_resource_name: The name of the shared private link resource. + Required. + :type shared_private_link_resource_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The shared private link resource. Required. + :type parameters: ~azure.mgmt.signalr.models.SharedPrivateLinkResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 SharedPrivateLinkResource or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SharedPrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + shared_private_link_resource_name: str, + resource_group_name: str, + resource_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.SharedPrivateLinkResource]: + """Create or update a shared private link resource. + :param shared_private_link_resource_name: The name of the shared private link resource. + Required. + :type shared_private_link_resource_name: str + :param resource_group_name: The name of the resource group that contains the resource. You can + obtain this value from the Azure Resource Manager API or the portal. Required. + :type resource_group_name: str + :param resource_name: The name of the resource. Required. + :type resource_name: str + :param parameters: The shared private link resource. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation 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 SharedPrivateLinkResource or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SharedPrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -395,20 +518,25 @@ def begin_create_or_update( shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, - parameters: "_models.SharedPrivateLinkResource", + parameters: Union[_models.SharedPrivateLinkResource, IO], **kwargs: Any - ) -> LROPoller["_models.SharedPrivateLinkResource"]: + ) -> LROPoller[_models.SharedPrivateLinkResource]: """Create or update a shared private link resource. :param shared_private_link_resource_name: The name of the shared private link resource. + Required. :type shared_private_link_resource_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str - :param parameters: The shared private link resource. - :type parameters: ~azure.mgmt.signalr.models.SharedPrivateLinkResource + :param parameters: The shared private link resource. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.signalr.models.SharedPrivateLinkResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -420,104 +548,114 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either SharedPrivateLinkResource or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.signalr.models.SharedPrivateLinkResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedPrivateLinkResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.SharedPrivateLinkResource] + 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( + raw_result = self._create_or_update_initial( # type: ignore shared_private_link_resource_name=shared_private_link_resource_name, resource_group_name=resource_group_name, resource_name=resource_name, 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): - response = pipeline_response.http_response - deserialized = self._deserialize('SharedPrivateLinkResource', pipeline_response) + deserialized = self._deserialize("SharedPrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore - def _delete_initial( - self, - shared_private_link_resource_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( shared_private_link_resource_name=shared_private_link_resource_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, - template_url=self._delete_initial.metadata['url'], + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore @distributed_trace def begin_delete( - self, - shared_private_link_resource_name: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + self, shared_private_link_resource_name: str, resource_group_name: str, resource_name: str, **kwargs: Any ) -> LROPoller[None]: """Delete the specified shared private link resource. :param shared_private_link_resource_name: The name of the shared private link resource. + Required. :type shared_private_link_resource_name: str :param resource_group_name: The name of the resource group that contains the resource. You can - obtain this value from the Azure Resource Manager API or the portal. + obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str - :param resource_name: The name of the resource. + :param resource_name: The name of the resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -529,41 +667,48 @@ def begin_delete( 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: """ - polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore shared_private_link_resource_name=shared_private_link_resource_name, resource_group_name=resource_group_name, resource_name=resource_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = 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, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}'} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}"} # type: ignore diff --git a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_usages_operations.py b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_usages_operations.py index 89fd41bb95d4..d8fb1c407b13 100644 --- a/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_usages_operations.py +++ b/sdk/signalr/azure-mgmt-signalr/azure/mgmt/signalr/operations/_usages_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,121 +6,136 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat -from msrest import Serializer from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - location: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = "2022-02-01" - accept = "application/json" + +def build_list_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/usages') + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/usages" + ) # pylint: disable=line-too-long path_format_arguments = { - "location": _SERIALIZER.url("location", location, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "location": _SERIALIZER.url("location", location, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) - -class UsagesOperations(object): - """UsagesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.signalr.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class UsagesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.signalr.SignalRManagementClient`'s + :attr:`usages` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - location: str, - **kwargs: Any - ) -> Iterable["_models.SignalRUsageList"]: + def list(self, location: str, **kwargs: Any) -> Iterable["_models.SignalRUsage"]: """List resource usage quotas by location. - :param location: the location like "eastus". + :param location: the location like "eastus". Required. :type location: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SignalRUsageList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SignalRUsageList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SignalRUsage or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.signalr.models.SignalRUsage] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SignalRUsageList"] + _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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SignalRUsageList] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( location=location, subscription_id=self._config.subscription_id, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - location=location, - subscription_id=self._config.subscription_id, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) + request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" return request @@ -133,7 +149,9 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(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]: @@ -143,8 +161,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.SignalRService/locations/{location}/usages'} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.SignalRService/locations/{location}/usages"} # type: ignore