From 921c77656c503d34a9a06870d9cb5f8b622b9ee1 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Mon, 12 Sep 2022 03:07:05 +0000 Subject: [PATCH] CodeGen from PR 20671 in Azure/azure-rest-api-specs Merge a5a9c1e30356c18e62aa46af3f18cb7be51d0755 into 5552a893886b8323c807e3a342332c31cd9ab93c --- .../azure-mgmt-reservations/_meta.json | 10 +- .../azure/mgmt/reservations/__init__.py | 16 +- .../reservations/_azure_reservation_api.py | 57 +- .../azure/mgmt/reservations/_configuration.py | 37 +- .../azure/mgmt/reservations/_patch.py | 2 +- .../azure/mgmt/reservations/_serialization.py | 1970 +++++++++++++ .../azure/mgmt/reservations/_vendor.py | 26 +- .../azure/mgmt/reservations/_version.py | 2 +- .../azure/mgmt/reservations/aio/__init__.py | 16 +- .../aio/_azure_reservation_api.py | 57 +- .../mgmt/reservations/aio/_configuration.py | 39 +- .../azure/mgmt/reservations/aio/_patch.py | 2 +- .../azure/mgmt/reservations/aio/_vendor.py | 28 + .../reservations/aio/operations/__init__.py | 26 +- .../_azure_reservation_api_operations.py | 115 +- .../_calculate_exchange_operations.py | 230 +- .../_calculate_refund_operations.py | 176 ++ .../aio/operations/_exchange_operations.py | 230 +- .../aio/operations/_operation_operations.py | 100 +- .../reservations/aio/operations/_patch.py | 20 + .../aio/operations/_quota_operations.py | 680 +++-- .../_quota_request_status_operations.py | 174 +- .../aio/operations/_reservation_operations.py | 1159 +++++--- .../_reservation_order_operations.py | 555 ++-- .../_return_operations_operations.py | 179 ++ .../mgmt/reservations/models/__init__.py | 278 +- .../models/_azure_reservation_api_enums.py | 106 +- .../mgmt/reservations/models/_models_py3.py | 2562 +++++++++-------- .../azure/mgmt/reservations/models/_patch.py | 20 + .../mgmt/reservations/operations/__init__.py | 26 +- .../_azure_reservation_api_operations.py | 184 +- .../_calculate_exchange_operations.py | 275 +- .../_calculate_refund_operations.py | 207 ++ .../operations/_exchange_operations.py | 275 +- .../operations/_operation_operations.py | 137 +- .../mgmt/reservations/operations/_patch.py | 20 + .../operations/_quota_operations.py | 875 +++--- .../_quota_request_status_operations.py | 267 +- .../operations/_reservation_operations.py | 1527 ++++++---- .../_reservation_order_operations.py | 730 +++-- .../_return_operations_operations.py | 208 ++ 41 files changed, 9336 insertions(+), 4267 deletions(-) create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_serialization.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_vendor.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_patch.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_patch.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_patch.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py diff --git a/sdk/reservations/azure-mgmt-reservations/_meta.json b/sdk/reservations/azure-mgmt-reservations/_meta.json index e5cf08c785d4..849801f59a21 100644 --- a/sdk/reservations/azure-mgmt-reservations/_meta.json +++ b/sdk/reservations/azure-mgmt-reservations/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "autorest": "3.8.4", "use": [ - "@autorest/python@5.13.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.1.5", + "@autorest/modelerfour@4.23.5" ], - "commit": "b1bbbab2f04c23e279c717f955d9a86bc4757946", + "commit": "faed328d0f9c39355cfe8cc86346a68e6f4e7228", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/reservations/resource-manager/readme.md --multiapi --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --use=@autorest/python@5.13.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/reservations/resource-manager/readme.md --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.1.5 --use=@autorest/modelerfour@4.23.5 --version=3.8.4 --version-tolerant=False", "readme": "specification/reservations/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py index b532c1a982f0..ce247e529086 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py @@ -10,9 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AzureReservationAPI'] -# `._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__ = ["AzureReservationAPI"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_azure_reservation_api.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_azure_reservation_api.py index d4e93e14837c..e7b1a14823b0 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_azure_reservation_api.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_azure_reservation_api.py @@ -9,20 +9,33 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models from ._configuration import AzureReservationAPIConfiguration -from .operations import AzureReservationAPIOperationsMixin, CalculateExchangeOperations, ExchangeOperations, OperationOperations, QuotaOperations, QuotaRequestStatusOperations, ReservationOperations, ReservationOrderOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + AzureReservationAPIOperationsMixin, + CalculateExchangeOperations, + CalculateRefundOperations, + ExchangeOperations, + OperationOperations, + QuotaOperations, + QuotaRequestStatusOperations, + ReservationOperations, + ReservationOrderOperations, + ReturnOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disable=too-many-instance-attributes + +class AzureReservationAPI( + AzureReservationAPIOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """This API describe Azure Reservation. :ivar reservation: ReservationOperations operations @@ -31,6 +44,10 @@ class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disa :vartype reservation_order: azure.mgmt.reservations.operations.ReservationOrderOperations :ivar operation: OperationOperations operations :vartype operation: azure.mgmt.reservations.operations.OperationOperations + :ivar calculate_refund: CalculateRefundOperations operations + :vartype calculate_refund: azure.mgmt.reservations.operations.CalculateRefundOperations + :ivar return_operations: ReturnOperations operations + :vartype return_operations: azure.mgmt.reservations.operations.ReturnOperations :ivar calculate_exchange: CalculateExchangeOperations operations :vartype calculate_exchange: azure.mgmt.reservations.operations.CalculateExchangeOperations :ivar exchange: ExchangeOperations operations @@ -39,7 +56,7 @@ class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disa :vartype quota: azure.mgmt.reservations.operations.QuotaOperations :ivar quota_request_status: QuotaRequestStatusOperations operations :vartype quota_request_status: azure.mgmt.reservations.operations.QuotaRequestStatusOperations - :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 base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -48,10 +65,7 @@ class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disa """ def __init__( - self, - credential: "TokenCredential", - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = AzureReservationAPIConfiguration(credential=credential, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) @@ -61,19 +75,24 @@ def __init__( self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.reservation = ReservationOperations(self._client, self._config, self._serialize, self._deserialize) - self.reservation_order = ReservationOrderOperations(self._client, self._config, self._serialize, self._deserialize) + self.reservation_order = ReservationOrderOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) - self.calculate_exchange = CalculateExchangeOperations(self._client, self._config, self._serialize, self._deserialize) + self.calculate_refund = CalculateRefundOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.return_operations = ReturnOperations(self._client, self._config, self._serialize, self._deserialize) + self.calculate_exchange = CalculateExchangeOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.exchange = ExchangeOperations(self._client, self._config, self._serialize, self._deserialize) self.quota = QuotaOperations(self._client, self._config, self._serialize, self._deserialize) - self.quota_request_status = QuotaRequestStatusOperations(self._client, self._config, self._serialize, self._deserialize) - + self.quota_request_status = QuotaRequestStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -82,7 +101,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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py index d7249e40deba..b9ce0aa7eef4 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py @@ -25,37 +25,34 @@ class AzureReservationAPIConfiguration(Configuration): # pylint: disable=too-ma 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 """ - def __init__( - self, - credential: "TokenCredential", - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: super(AzureReservationAPIConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-reservations/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-reservations/{}".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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_patch.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_serialization.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py index 138f663c53a4..5c6e33631785 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py @@ -5,8 +5,20 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from abc import ABC +from typing import TYPE_CHECKING + from azure.core.pipeline.transport import HttpRequest +from ._configuration import AzureReservationAPIConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import PipelineClient + + from ._serialization import Deserializer, Serializer + + def _convert_request(request, files=None): data = request.content if not files else None request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) @@ -14,6 +26,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -21,7 +34,14 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) + + +class MixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: AzureReservationAPIConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_version.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_version.py index 48944bf3938a..e5754a47ce68 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_version.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py index 099f702e574c..8c8db752ac9a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py @@ -7,9 +7,15 @@ # -------------------------------------------------------------------------- from ._azure_reservation_api import AzureReservationAPI -__all__ = ['AzureReservationAPI'] -# `._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__ = ["AzureReservationAPI"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_azure_reservation_api.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_azure_reservation_api.py index 155f7bea7dc3..bd8d49121e43 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_azure_reservation_api.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_azure_reservation_api.py @@ -9,20 +9,33 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models +from .._serialization import Deserializer, Serializer from ._configuration import AzureReservationAPIConfiguration -from .operations import AzureReservationAPIOperationsMixin, CalculateExchangeOperations, ExchangeOperations, OperationOperations, QuotaOperations, QuotaRequestStatusOperations, ReservationOperations, ReservationOrderOperations +from .operations import ( + AzureReservationAPIOperationsMixin, + CalculateExchangeOperations, + CalculateRefundOperations, + ExchangeOperations, + OperationOperations, + QuotaOperations, + QuotaRequestStatusOperations, + ReservationOperations, + ReservationOrderOperations, + ReturnOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disable=too-many-instance-attributes + +class AzureReservationAPI( + AzureReservationAPIOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """This API describe Azure Reservation. :ivar reservation: ReservationOperations operations @@ -31,6 +44,10 @@ class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disa :vartype reservation_order: azure.mgmt.reservations.aio.operations.ReservationOrderOperations :ivar operation: OperationOperations operations :vartype operation: azure.mgmt.reservations.aio.operations.OperationOperations + :ivar calculate_refund: CalculateRefundOperations operations + :vartype calculate_refund: azure.mgmt.reservations.aio.operations.CalculateRefundOperations + :ivar return_operations: ReturnOperations operations + :vartype return_operations: azure.mgmt.reservations.aio.operations.ReturnOperations :ivar calculate_exchange: CalculateExchangeOperations operations :vartype calculate_exchange: azure.mgmt.reservations.aio.operations.CalculateExchangeOperations :ivar exchange: ExchangeOperations operations @@ -40,7 +57,7 @@ class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disa :ivar quota_request_status: QuotaRequestStatusOperations operations :vartype quota_request_status: azure.mgmt.reservations.aio.operations.QuotaRequestStatusOperations - :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 base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -49,10 +66,7 @@ class AzureReservationAPI(AzureReservationAPIOperationsMixin): # pylint: disa """ def __init__( - self, - credential: "AsyncTokenCredential", - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = AzureReservationAPIConfiguration(credential=credential, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) @@ -62,19 +76,24 @@ def __init__( self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.reservation = ReservationOperations(self._client, self._config, self._serialize, self._deserialize) - self.reservation_order = ReservationOrderOperations(self._client, self._config, self._serialize, self._deserialize) + self.reservation_order = ReservationOrderOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) - self.calculate_exchange = CalculateExchangeOperations(self._client, self._config, self._serialize, self._deserialize) + self.calculate_refund = CalculateRefundOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.return_operations = ReturnOperations(self._client, self._config, self._serialize, self._deserialize) + self.calculate_exchange = CalculateExchangeOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.exchange = ExchangeOperations(self._client, self._config, self._serialize, self._deserialize) self.quota = QuotaOperations(self._client, self._config, self._serialize, self._deserialize) - self.quota_request_status = QuotaRequestStatusOperations(self._client, self._config, self._serialize, self._deserialize) - + self.quota_request_status = QuotaRequestStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -83,7 +102,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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py index 536ad9e6922d..a22504dccc2d 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py @@ -25,36 +25,31 @@ class AzureReservationAPIConfiguration(Configuration): # pylint: disable=too-ma 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 """ - def __init__( - self, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: super(AzureReservationAPIConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-reservations/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-reservations/{}".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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_patch.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_vendor.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_vendor.py new file mode 100644 index 000000000000..985979c1d804 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_vendor.py @@ -0,0 +1,28 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import TYPE_CHECKING + +from azure.core.pipeline.transport import HttpRequest + +from ._configuration import AzureReservationAPIConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core import AsyncPipelineClient + + from .._serialization import Deserializer, Serializer + + +class MixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: AzureReservationAPIConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py index 5cf631a610fd..7ae269dcb4f4 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py @@ -10,18 +10,28 @@ from ._azure_reservation_api_operations import AzureReservationAPIOperationsMixin from ._reservation_order_operations import ReservationOrderOperations from ._operation_operations import OperationOperations +from ._calculate_refund_operations import CalculateRefundOperations +from ._return_operations_operations import ReturnOperations from ._calculate_exchange_operations import CalculateExchangeOperations from ._exchange_operations import ExchangeOperations from ._quota_operations import QuotaOperations from ._quota_request_status_operations import QuotaRequestStatusOperations +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__ = [ - 'ReservationOperations', - 'AzureReservationAPIOperationsMixin', - 'ReservationOrderOperations', - 'OperationOperations', - 'CalculateExchangeOperations', - 'ExchangeOperations', - 'QuotaOperations', - 'QuotaRequestStatusOperations', + "ReservationOperations", + "AzureReservationAPIOperationsMixin", + "ReservationOrderOperations", + "OperationOperations", + "CalculateRefundOperations", + "ReturnOperations", + "CalculateExchangeOperations", + "ExchangeOperations", + "QuotaOperations", + "QuotaRequestStatusOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py index bf01dc6ab1d9..07e5d9863f56 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py @@ -8,21 +8,34 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, List, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request -from ...operations._azure_reservation_api_operations import build_get_applied_reservation_list_request, build_get_catalog_request -T = TypeVar('T') +from ...operations._azure_reservation_api_operations import ( + build_get_applied_reservation_list_request, + build_get_catalog_request, +) +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AzureReservationAPIOperationsMixin: +class AzureReservationAPIOperationsMixin(MixinABC): @distributed_trace_async async def get_catalog( self, @@ -33,14 +46,14 @@ async def get_catalog( offer_id: Optional[str] = None, plan_id: Optional[str] = None, **kwargs: Any - ) -> List["_models.Catalog"]: + ) -> List[_models.Catalog]: """Get the regions and skus that are available for RI purchase for the specified Azure subscription. Get the regions and skus that are available for RI purchase for the specified Azure subscription. - :param subscription_id: Id of the subscription. + :param subscription_id: Id of the subscription. Required. :type subscription_id: str :param reserved_resource_type: The type of the resource for which the skus should be provided. Default value is None. @@ -54,41 +67,44 @@ async def get_catalog( :type offer_id: str :param plan_id: Plan id used to get the third party products. Default value is None. :type plan_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: list of Catalog, or the result of cls(response) + :return: list of Catalog or the result of cls(response) :rtype: list[~azure.mgmt.reservations.models.Catalog] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[List["_models.Catalog"]] 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', "2022-03-01") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[List[_models.Catalog]] - request = build_get_catalog_request( subscription_id=subscription_id, - api_version=api_version, reserved_resource_type=reserved_resource_type, location=location, publisher_id=publisher_id, offer_id=offer_id, plan_id=plan_id, - template_url=self.get_catalog.metadata['url'], + api_version=api_version, + template_url=self.get_catalog.metadata["url"], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -96,59 +112,57 @@ async def get_catalog( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('[Catalog]', pipeline_response) + deserialized = self._deserialize("[Catalog]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_catalog.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs"} # type: ignore - + get_catalog.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs"} # type: ignore @distributed_trace_async - async def get_applied_reservation_list( - self, - subscription_id: str, - **kwargs: Any - ) -> "_models.AppliedReservations": + async def get_applied_reservation_list(self, subscription_id: str, **kwargs: Any) -> _models.AppliedReservations: """Get list of applicable ``Reservation``\ s. Get applicable ``Reservation``\ s that are applied to this subscription or a resource group under this subscription. - :param subscription_id: Id of the subscription. + :param subscription_id: Id of the subscription. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AppliedReservations, or the result of cls(response) + :return: AppliedReservations or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.AppliedReservations - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AppliedReservations"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AppliedReservations] - request = build_get_applied_reservation_list_request( subscription_id=subscription_id, api_version=api_version, - template_url=self.get_applied_reservation_list.metadata['url'], + template_url=self.get_applied_reservation_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 - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -156,12 +170,11 @@ async def get_applied_reservation_list( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AppliedReservations', pipeline_response) + deserialized = self._deserialize("AppliedReservations", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_applied_reservation_list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations"} # type: ignore - + get_applied_reservation_list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py index 5e59baffcd56..295f96007e18 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py @@ -6,115 +6,191 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._calculate_exchange_operations import build_post_request_initial -T = TypeVar('T') +from ...operations._calculate_exchange_operations import build_post_request +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class CalculateExchangeOperations: - """CalculateExchangeOperations 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 CalculateExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.aio.AzureReservationAPI`'s + :attr:`calculate_exchange` 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") async def _post_initial( - self, - body: "_models.CalculateExchangeRequest", - **kwargs: Any - ) -> Optional["_models.CalculateExchangeOperationResultResponse"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.CalculateExchangeOperationResultResponse"]] + self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any + ) -> Optional[_models.CalculateExchangeOperationResultResponse]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CalculateExchangeOperationResultResponse]] - _json = self._serialize.body(body, 'CalculateExchangeRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CalculateExchangeRequest") - request = build_post_request_initial( + request = build_post_request( api_version=api_version, content_type=content_type, json=_json, - template_url=self._post_initial.metadata['url'], + content=_content, + template_url=self._post_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('CalculateExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("CalculateExchangeOperationResultResponse", pipeline_response) if response.status_code == 202: - response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) - + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _post_initial.metadata = {'url': "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore + _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore + + @overload + async def begin_post( + self, body: _models.CalculateExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: Request containing purchases and refunds that need to be executed. Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 + CalculateExchangeOperationResultResponse or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: Request containing purchases and refunds that need to be executed. Required. + :type body: 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 + CalculateExchangeOperationResultResponse or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_post( - self, - body: "_models.CalculateExchangeRequest", - **kwargs: Any - ) -> AsyncLROPoller["_models.CalculateExchangeOperationResultResponse"]: + self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: """Calculates the refund amounts and price of the new purchases. Calculates price for exchanging ``Reservations`` if there are no policy errors. - :param body: Request containing purchases and refunds that need to be executed. - :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param body: Request containing purchases and refunds that need to be executed. Is either a + model type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -127,45 +203,51 @@ async def begin_post( CalculateExchangeOperationResultResponse or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.CalculateExchangeOperationResultResponse"] - 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", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CalculateExchangeOperationResultResponse] + 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._post_initial( + raw_result = await self._post_initial( # type: ignore body=body, 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('CalculateExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("CalculateExchangeOperationResultResponse", 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, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_post.metadata = {'url': "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore + begin_post.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py new file mode 100644 index 000000000000..841cd9538daa --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py @@ -0,0 +1,176 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._calculate_refund_operations import build_post_request +from .._vendor import MixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class CalculateRefundOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s + :attr:`calculate_refund` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def post( + self, + reservation_order_id: str, + body: _models.CalculateRefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CalculateRefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: 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: CalculateRefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def post( + self, reservation_order_id: str, body: Union[_models.CalculateRefundRequest, IO], **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Is either a model type + or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: CalculateRefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CalculateRefundResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CalculateRefundRequest") + + request = build_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.post.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CalculateRefundResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/calculateRefund"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py index b6bfcc7c1161..e8a372816178 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py @@ -6,115 +6,191 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._exchange_operations import build_post_request_initial -T = TypeVar('T') +from ...operations._exchange_operations import build_post_request +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ExchangeOperations: - """ExchangeOperations 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 ExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.aio.AzureReservationAPI`'s + :attr:`exchange` 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") async def _post_initial( - self, - body: "_models.ExchangeRequest", - **kwargs: Any - ) -> Optional["_models.ExchangeOperationResultResponse"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExchangeOperationResultResponse"]] + self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any + ) -> Optional[_models.ExchangeOperationResultResponse]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ExchangeOperationResultResponse]] - _json = self._serialize.body(body, 'ExchangeRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ExchangeRequest") - request = build_post_request_initial( + request = build_post_request( api_version=api_version, content_type=content_type, json=_json, - template_url=self._post_initial.metadata['url'], + content=_content, + template_url=self._post_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('ExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("ExchangeOperationResultResponse", pipeline_response) if response.status_code == 202: - response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) - + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _post_initial.metadata = {'url': "/providers/Microsoft.Capacity/exchange"} # type: ignore + _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} # type: ignore + + @overload + async def begin_post( + self, body: _models.ExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: Request containing the refunds and purchases that need to be executed. Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 ExchangeOperationResultResponse or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: Request containing the refunds and purchases that need to be executed. Required. + :type body: 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 ExchangeOperationResultResponse or + the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_post( - self, - body: "_models.ExchangeRequest", - **kwargs: Any - ) -> AsyncLROPoller["_models.ExchangeOperationResultResponse"]: + self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: """Exchange Reservation(s). Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - :param body: Request containing the refunds and purchases that need to be executed. - :type body: ~azure.mgmt.reservations.models.ExchangeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param body: Request containing the refunds and purchases that need to be executed. Is either a + model type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -127,45 +203,51 @@ async def begin_post( the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExchangeOperationResultResponse"] - 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", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExchangeOperationResultResponse] + 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._post_initial( + raw_result = await self._post_initial( # type: ignore body=body, 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('ExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("ExchangeOperationResultResponse", 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, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_post.metadata = {'url': "/providers/Microsoft.Capacity/exchange"} # type: ignore + begin_post.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py index 47074b6254f0..f8f2e9c0afac 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py @@ -9,83 +9,91 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operation_operations import build_list_request -T = TypeVar('T') +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class OperationOperations: - """OperationOperations 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 OperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.aio.AzureReservationAPI`'s + :attr:`operation` 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.OperationResponse"]: """Get operations. List all the operations. - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.OperationList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either OperationResponse or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.OperationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationList] - 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( api_version=api_version, - template_url=self.list.metadata['url'], + 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( - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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,10 +107,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -113,8 +119,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.Capacity/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Capacity/operations"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py index 8218f8c9de86..72f87266d342 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py @@ -6,101 +6,113 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod 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._quota_operations import build_create_or_update_request_initial, build_get_request, build_list_request, build_update_request_initial -T = TypeVar('T') +from ...operations._quota_operations import ( + build_create_or_update_request, + build_get_request, + build_list_request, + build_update_request, +) +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class QuotaOperations: - """QuotaOperations 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 QuotaOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.aio.AzureReservationAPI`'s + :attr:`quota` 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 async def get( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - **kwargs: Any - ) -> "_models.CurrentQuotaLimitBase": + self, subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any + ) -> _models.CurrentQuotaLimitBase: """Get the current quota (service limit) and usage of a resource. You can use the response from the GET operation to submit quota update request. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param resource_name: The resource name for a resource provider, such as SKU name for Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. :type resource_name: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CurrentQuotaLimitBase, or the result of cls(response) + :return: CurrentQuotaLimitBase or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CurrentQuotaLimitBase"] 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 {}) - api_version = kwargs.pop('api_version', "2020-10-25") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CurrentQuotaLimitBase] - request = build_get_request( subscription_id=subscription_id, provider_id=provider_id, location=location, resource_name=resource_name, api_version=api_version, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -109,17 +121,16 @@ async def get( raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore async def _create_or_update_initial( self, @@ -127,21 +138,35 @@ async def _create_or_update_initial( provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], **kwargs: Any - ) -> Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]: - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] + ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(create_quota_request, 'CurrentQuotaLimitBase') - - request = build_create_or_update_request_initial( + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop( + "cls", None + ) # type: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_quota_request, (IO, bytes)): + _content = create_quota_request + else: + _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") + + request = build_create_or_update_request( subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -149,75 +174,182 @@ async def _create_or_update_initial( api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.ExceptionResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('QuotaRequestSubmitResponse201', pipeline_response) + deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + + @overload + async def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Union[AsyncLROPoller[_models.CurrentQuotaLimitBase], AsyncLROPoller[_models.QuotaRequestSubmitResponse201]]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + #. Make the Get request to get the quota information for specific resource. + #. To increase the quota, update the limit field in the response from Get request to new value. + #. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to + update the quota. - @distributed_trace_async + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 CurrentQuotaLimitBase or An instance + of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload async def begin_create_or_update( self, subscription_id: str, provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: IO, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]]: + ) -> Union[AsyncLROPoller[_models.CurrentQuotaLimitBase], AsyncLROPoller[_models.QuotaRequestSubmitResponse201]]: """Create or update the quota (service limits) of a resource to the requested value. Steps: - #. - Make the Get request to get the quota information for specific resource. + #. Make the Get request to get the quota information for specific resource. + #. To increase the quota, update the limit field in the response from Get request to new value. + #. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to + update the quota. + + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 CurrentQuotaLimitBase or An instance + of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], + **kwargs: Any + ) -> Union[AsyncLROPoller[_models.CurrentQuotaLimitBase], AsyncLROPoller[_models.QuotaRequestSubmitResponse201]]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: - #. - To increase the quota, update the limit field in the response from Get request to new value. - #. - Submit the JSON to the quota request API to update the quota. + #. Make the Get request to get the quota information for specific resource. + #. To increase the quota, update the limit field in the response from Get request to new value. + #. Submit the JSON to the quota request API to update the quota. The Create quota request may be constructed as follows. The PUT operation can be used to update the quota. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param resource_name: The resource name for a resource provider, such as SKU name for Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. :type resource_name: str - :param create_quota_request: Quota requests payload. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param create_quota_request: Quota requests payload. Is either a model type or a IO type. + Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -226,24 +358,25 @@ async def begin_create_or_update( :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 CurrentQuotaLimitBase or - QuotaRequestSubmitResponse201 or the result of cls(response) + :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance + of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of + cls(response) :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase or - ~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] - 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", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CurrentQuotaLimitBase] + 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 subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -251,32 +384,38 @@ async def begin_create_or_update( create_quota_request=create_quota_request, 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('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", 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': 'original-uri'}, **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": "original-uri"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore async def _update_initial( self, @@ -284,21 +423,35 @@ async def _update_initial( provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], **kwargs: Any - ) -> Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]: - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] + ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(create_quota_request, 'CurrentQuotaLimitBase') - - request = build_update_request_initial( + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop( + "cls", None + ) # type: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_quota_request, (IO, bytes)): + _content = create_quota_request + else: + _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") + + request = build_update_request( subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -306,70 +459,173 @@ async def _update_initial( 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.ExceptionResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('QuotaRequestSubmitResponse201', pipeline_response) + deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore - @distributed_trace_async + @overload async def begin_update( self, subscription_id: str, provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]]: + ) -> Union[AsyncLROPoller[_models.CurrentQuotaLimitBase], AsyncLROPoller[_models.QuotaRequestSubmitResponse201]]: """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. + • To increase the quota, update the limit field from the GET response to a new value. + • To update the quota value, submit the JSON response to the quota request API to update the + quota. + • To update the quota. use the PATCH operation. + + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 CurrentQuotaLimitBase or An instance + of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ + @overload + async def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Union[AsyncLROPoller[_models.CurrentQuotaLimitBase], AsyncLROPoller[_models.QuotaRequestSubmitResponse201]]: + """Update the quota (service limits) of this resource to the requested value. + • To get the quota information for specific resource, send a GET request. • To increase the quota, update the limit field from the GET response to a new value. + • To update the quota value, submit the JSON response to the quota request API to update the + quota. + • To update the quota. use the PATCH operation. + + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 CurrentQuotaLimitBase or An instance + of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace_async + async def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], + **kwargs: Any + ) -> Union[AsyncLROPoller[_models.CurrentQuotaLimitBase], AsyncLROPoller[_models.QuotaRequestSubmitResponse201]]: + """Update the quota (service limits) of this resource to the requested value. + • To get the quota information for specific resource, send a GET request. + • To increase the quota, update the limit field from the GET response to a new value. • To update the quota value, submit the JSON response to the quota request API to update the quota. • To update the quota. use the PATCH operation. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param resource_name: The resource name for a resource provider, such as SKU name for Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. :type resource_name: str - :param create_quota_request: Payload for the quota request. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param create_quota_request: Payload for the quota request. Is either a model type or a IO + type. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -378,24 +634,25 @@ async def begin_update( :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 CurrentQuotaLimitBase or - QuotaRequestSubmitResponse201 or the result of cls(response) + :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance + of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of + cls(response) :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase or - ~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] - 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", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CurrentQuotaLimitBase] + 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 subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -403,89 +660,92 @@ async def begin_update( create_quota_request=create_quota_request, 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('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", 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': 'original-uri'}, **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": "original-uri"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore @distributed_trace def list( - self, - subscription_id: str, - provider_id: str, - location: str, - **kwargs: Any - ) -> AsyncIterable["_models.QuotaLimits"]: + self, subscription_id: str, provider_id: str, location: str, **kwargs: Any + ) -> AsyncIterable["_models.CurrentQuotaLimitBase"]: """Gets a list of current quotas (service limits) and usage for all resources. The response from the list quota operation can be leveraged to request quota updates. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either QuotaLimits or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.QuotaLimits] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CurrentQuotaLimitBase or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QuotaLimits] - cls = kwargs.pop('cls', None) # type: ClsType["_models.QuotaLimits"] 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=subscription_id, provider_id=provider_id, location=location, api_version=api_version, - template_url=self.list.metadata['url'], + 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=subscription_id, - provider_id=provider_id, - location=location, - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -499,10 +759,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -513,8 +771,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.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py index e8b05cc8d928..701425c1261f 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py @@ -9,96 +9,102 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest 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._quota_request_status_operations import build_get_request, build_list_request -T = TypeVar('T') +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class QuotaRequestStatusOperations: - """QuotaRequestStatusOperations 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 QuotaRequestStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.aio.AzureReservationAPI`'s + :attr:`quota_request_status` 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 async def get( - self, - subscription_id: str, - provider_id: str, - location: str, - id: str, - **kwargs: Any - ) -> "_models.QuotaRequestDetails": + self, subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any + ) -> _models.QuotaRequestDetails: """For the specified Azure region (location), get the details and status of the quota request by the quota request ID for the resources of the resource provider. The PUT request for the quota (service limit) returns a response with the requestId parameter. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str - :param id: Quota Request ID. + :param id: Quota Request ID. Required. :type id: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QuotaRequestDetails, or the result of cls(response) + :return: QuotaRequestDetails or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.QuotaRequestDetails - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QuotaRequestDetails"] 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', "2020-10-25") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QuotaRequestDetails] - request = build_get_request( subscription_id=subscription_id, provider_id=provider_id, location=location, id=id, api_version=api_version, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -106,15 +112,14 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ExceptionResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QuotaRequestDetails', pipeline_response) + deserialized = self._deserialize("QuotaRequestDetails", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}"} # type: ignore @distributed_trace def list( @@ -126,26 +131,24 @@ def list( top: Optional[int] = None, skiptoken: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.QuotaRequestDetailsList"]: + ) -> AsyncIterable["_models.QuotaRequestDetails"]: """For the specified Azure region (location), subscription, and resource provider, get the history of the quota requests for the past year. To select specific quota requests, use the oData filter. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param filter: .. list-table:: :header-rows: 1 * - Field - Supported operators - * - - - - |requestSubmitTime | ge, le, eq, gt, lt. Default value is None. + * - requestSubmitTime + - ge, le, eq, gt, lt. Default value is None. :type filter: str :param top: Number of records to return. Default value is None. :type top: int @@ -154,53 +157,48 @@ def list( skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either QuotaRequestDetailsList or the result of - cls(response) + :return: An iterator like instance of either QuotaRequestDetails or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetailsList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetails] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QuotaRequestDetailsList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.QuotaRequestDetailsList"] 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=subscription_id, provider_id=provider_id, location=location, - api_version=api_version, filter=filter, top=top, skiptoken=skiptoken, - 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( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - api_version=api_version, - filter=filter, - top=top, - skiptoken=skiptoken, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -214,10 +212,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -228,8 +224,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.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py index c4030fe08e9e..4c50740f94ba 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py @@ -6,118 +6,227 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, List, Optional, TypeVar, Union +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod 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._reservation_operations import build_available_scopes_request_initial, build_get_request, build_list_all_request, build_list_request, build_list_revisions_request, build_merge_request_initial, build_split_request_initial, build_update_request_initial -T = TypeVar('T') +from ...operations._reservation_operations import ( + build_archive_request, + build_available_scopes_request, + build_get_request, + build_list_all_request, + build_list_request, + build_list_revisions_request, + build_merge_request, + build_split_request, + build_unarchive_request, + build_update_request, +) +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ReservationOperations: - """ReservationOperations 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 ReservationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.aio.AzureReservationAPI`'s + :attr:`reservation` 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") async def _available_scopes_initial( self, reservation_order_id: str, reservation_id: str, - body: "_models.AvailableScopeRequest", + body: Union[_models.AvailableScopeRequest, IO], **kwargs: Any - ) -> "_models.AvailableScopeProperties": - cls = kwargs.pop('cls', None) # type: ClsType["_models.AvailableScopeProperties"] + ) -> _models.AvailableScopeProperties: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - 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(body, 'AvailableScopeRequest') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableScopeProperties] - request = build_available_scopes_request_initial( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "AvailableScopeRequest") + + request = build_available_scopes_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._available_scopes_initial.metadata['url'], + content=_content, + template_url=self._available_scopes_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AvailableScopeProperties', pipeline_response) + deserialized = self._deserialize("AvailableScopeProperties", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _available_scopes_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore + _available_scopes_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore + + @overload + async def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: _models.AvailableScopeRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Get Available Scopes for ``Reservation``. + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param body: Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 AvailableScopeProperties or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Get Available Scopes for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param body: Required. + :type body: 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 AvailableScopeProperties or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_available_scopes( self, reservation_order_id: str, reservation_id: str, - body: "_models.AvailableScopeRequest", + body: Union[_models.AvailableScopeRequest, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.AvailableScopeProperties"]: + ) -> AsyncLROPoller[_models.AvailableScopeProperties]: """Get Available Scopes for ``Reservation``. Get Available Scopes for ``Reservation``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param body: - :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param body: Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -130,119 +239,135 @@ async def begin_available_scopes( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.AvailableScopeProperties"] - 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", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableScopeProperties] + 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._available_scopes_initial( + raw_result = await self._available_scopes_initial( # type: ignore reservation_order_id=reservation_order_id, reservation_id=reservation_id, body=body, 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('AvailableScopeProperties', pipeline_response) + deserialized = self._deserialize("AvailableScopeProperties", 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, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_available_scopes.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore + begin_available_scopes.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore async def _split_initial( - self, - reservation_order_id: str, - body: "_models.SplitRequest", - **kwargs: Any - ) -> Optional[List["_models.ReservationResponse"]]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional[List["_models.ReservationResponse"]]] + self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any + ) -> Optional[List[_models.ReservationResponse]]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - 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(body, 'SplitRequest') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[List[_models.ReservationResponse]]] - request = build_split_request_initial( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "SplitRequest") + + request = build_split_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._split_initial.metadata['url'], + content=_content, + template_url=self._split_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _split_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore - + _split_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore - @distributed_trace_async + @overload async def begin_split( self, reservation_order_id: str, - body: "_models.SplitRequest", + body: _models.SplitRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[List["_models.ReservationResponse"]]: + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: """Split the ``Reservation``. Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed to Split a reservation item. + :param body: Information needed to Split a reservation item. Required. :type body: ~azure.mgmt.reservations.models.SplitRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -255,119 +380,198 @@ async def begin_split( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[List["_models.ReservationResponse"]] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_split( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: 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 list of ReservationResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_split( + self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Is either a model type or a IO + type. Required. + :type body: ~azure.mgmt.reservations.models.SplitRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[List[_models.ReservationResponse]] + 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._split_initial( + raw_result = await self._split_initial( # type: ignore reservation_order_id=reservation_order_id, body=body, 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('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", 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': 'location'}, **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, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_split.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore + begin_split.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore async def _merge_initial( - self, - reservation_order_id: str, - body: "_models.MergeRequest", - **kwargs: Any - ) -> Optional[List["_models.ReservationResponse"]]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional[List["_models.ReservationResponse"]]] + self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any + ) -> Optional[List[_models.ReservationResponse]]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - 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(body, 'MergeRequest') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[List[_models.ReservationResponse]]] - request = build_merge_request_initial( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "MergeRequest") + + request = build_merge_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._merge_initial.metadata['url'], + content=_content, + template_url=self._merge_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _merge_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore - + _merge_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore - @distributed_trace_async + @overload async def begin_merge( self, reservation_order_id: str, - body: "_models.MergeRequest", + body: _models.MergeRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[List["_models.ReservationResponse"]]: + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: """Merges two ``Reservation``\ s. Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s being merged must have same properties. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. + :param body: Information needed for commercial request for a reservation. Required. :type body: ~azure.mgmt.reservations.models.MergeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -380,98 +584,163 @@ async def begin_merge( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[List["_models.ReservationResponse"]] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_merge( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``\ s. + + Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s + being merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: 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 list of ReservationResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_merge( + self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``\ s. + + Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s + being merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Is either a model + type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.MergeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[List[_models.ReservationResponse]] + 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._merge_initial( + raw_result = await self._merge_initial( # type: ignore reservation_order_id=reservation_order_id, body=body, 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('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", 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': 'location'}, **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, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_merge.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore + begin_merge.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore @distributed_trace - def list( - self, - reservation_order_id: str, - **kwargs: Any - ) -> AsyncIterable["_models.ReservationList"]: + def list(self, reservation_order_id: str, **kwargs: Any) -> AsyncIterable["_models.ReservationResponse"]: """Get ``Reservation``\ s in a given reservation Order. List ``Reservation``\ s within a single ``ReservationOrder``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationList or the result of cls(response) + :return: An iterator like instance of either ReservationResponse or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationList"] 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( reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list.metadata['url'], + 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( - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -485,10 +754,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -499,62 +766,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': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations"} # type: ignore @distributed_trace_async async def get( - self, - reservation_id: str, - reservation_order_id: str, - expand: Optional[str] = None, - **kwargs: Any - ) -> "_models.ReservationResponse": + self, reservation_id: str, reservation_order_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationResponse: """Get ``Reservation`` details. Get specific ``Reservation`` details. - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param expand: Supported value of this query is renewProperties. Default value is None. :type expand: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationResponse, or the result of cls(response) + :return: ReservationResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.ReservationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationResponse"] 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', "2022-03-01") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationResponse] - request = build_get_request( reservation_id=reservation_id, reservation_order_id=reservation_order_id, - api_version=api_version, expand=expand, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -562,89 +826,100 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ReservationResponse', pipeline_response) + deserialized = self._deserialize("ReservationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore - + get.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore async def _update_initial( - self, - reservation_order_id: str, - reservation_id: str, - parameters: "_models.Patch", - **kwargs: Any - ) -> Optional["_models.ReservationResponse"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ReservationResponse"]] + self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any + ) -> Optional[_models.ReservationResponse]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - 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, 'Patch') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ReservationResponse]] - request = build_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, "Patch") + + request = build_update_request( reservation_order_id=reservation_order_id, reservation_id=reservation_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ReservationResponse', pipeline_response) + deserialized = self._deserialize("ReservationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore - + _update_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore - @distributed_trace_async + @overload async def begin_update( self, reservation_order_id: str, reservation_id: str, - parameters: "_models.Patch", + parameters: _models.Patch, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.ReservationResponse"]: + ) -> AsyncLROPoller[_models.ReservationResponse]: """Updates a ``Reservation``. Updates the applied scopes of the ``Reservation``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param parameters: Information needed to patch a reservation item. + :param parameters: Information needed to patch a reservation item. Required. :type parameters: ~azure.mgmt.reservations.models.Patch - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -656,104 +931,289 @@ async def begin_update( :return: An instance of AsyncLROPoller that returns either ReservationResponse or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationResponse"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. 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 ReservationResponse or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.reservations.models.Patch or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ReservationResponse or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationResponse] + 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 reservation_order_id=reservation_order_id, reservation_id=reservation_id, 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('ReservationResponse', pipeline_response) + deserialized = self._deserialize("ReservationResponse", 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, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore + begin_update.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore + + @distributed_trace_async + async def archive( # pylint: disable=inconsistent-return-statements + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> None: + """Archive a ``Reservation``. + + Archiving a ``Reservation`` moves it to ``Archived`` state. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_archive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + template_url=self.archive.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + archive.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/archive"} # type: ignore + + @distributed_trace_async + async def unarchive( # pylint: disable=inconsistent-return-statements + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> None: + """Unarchive a ``Reservation``. + + Unarchiving a ``Reservation`` moves it to the state it was before archiving. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_unarchive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + template_url=self.unarchive.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + unarchive.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/unarchive"} # type: ignore @distributed_trace def list_revisions( - self, - reservation_id: str, - reservation_order_id: str, - **kwargs: Any - ) -> AsyncIterable["_models.ReservationList"]: + self, reservation_id: str, reservation_order_id: str, **kwargs: Any + ) -> AsyncIterable["_models.ReservationResponse"]: """Get ``Reservation`` revisions. List of all the revisions for the ``Reservation``. - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationList or the result of cls(response) + :return: An iterator like instance of either ReservationResponse or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationList"] 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_revisions_request( reservation_id=reservation_id, reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list_revisions.metadata['url'], + template_url=self.list_revisions.metadata["url"], + 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_revisions_request( - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -767,10 +1227,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -781,11 +1239,9 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_revisions.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions"} # type: ignore + list_revisions.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions"} # type: ignore @distributed_trace def list_all( @@ -797,7 +1253,7 @@ def list_all( selected_state: Optional[str] = None, take: Optional[float] = None, **kwargs: Any - ) -> AsyncIterable["_models.ReservationsListResult"]: + ) -> AsyncIterable["_models.ReservationResponse"]: """List the reservations and the roll up counts of reservations group by provisioning states that the user has access to in the current tenant. @@ -820,53 +1276,48 @@ def list_all( :type selected_state: str :param take: To number of reservations to return. Default value is None. :type take: float - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationsListResult or the result of - cls(response) + :return: An iterator like instance of either ReservationResponse or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationsListResult"] 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_all_request( - api_version=api_version, filter=filter, orderby=orderby, refresh_summary=refresh_summary, skiptoken=skiptoken, selected_state=selected_state, take=take, - template_url=self.list_all.metadata['url'], + api_version=api_version, + template_url=self.list_all.metadata["url"], + 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_all_request( - api_version=api_version, - filter=filter, - orderby=orderby, - refresh_summary=refresh_summary, - skiptoken=skiptoken, - selected_state=selected_state, - take=take, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -880,10 +1331,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -894,8 +1343,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_all.metadata = {'url': "/providers/Microsoft.Capacity/reservations"} # type: ignore + list_all.metadata = {"url": "/providers/Microsoft.Capacity/reservations"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py index 4bdadf0812f9..90a99a115ed6 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py @@ -6,92 +6,157 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod 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._reservation_order_operations import build_calculate_request, build_change_directory_request, build_get_request, build_list_request, build_purchase_request_initial -T = TypeVar('T') +from ...operations._reservation_order_operations import ( + build_calculate_request, + build_change_directory_request, + build_get_request, + build_list_request, + build_purchase_request, +) +from .._vendor import MixinABC + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ReservationOrderOperations: - """ReservationOrderOperations 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 ReservationOrderOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.aio.AzureReservationAPI`'s + :attr:`reservation_order` 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 calculate( - self, - body: "_models.PurchaseRequest", - **kwargs: Any - ) -> "_models.CalculatePriceResponse": + self, body: _models.PurchaseRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: """Calculate price for a ``ReservationOrder``. Calculate price for placing a ``ReservationOrder``. - :param body: Information needed for calculate or purchase reservation. + :param body: Information needed for calculate or purchase reservation. Required. :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CalculatePriceResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def calculate( + self, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: Information needed for calculate or purchase reservation. Required. + :type body: 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: CalculatePriceResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def calculate( + self, body: Union[_models.PurchaseRequest, IO], **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: Information needed for calculate or purchase reservation. Is either a model type + or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: CalculatePriceResponse, or the result of cls(response) + :return: CalculatePriceResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CalculatePriceResponse"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CalculatePriceResponse] - _json = self._serialize.body(body, 'PurchaseRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "PurchaseRequest") request = build_calculate_request( api_version=api_version, content_type=content_type, json=_json, - template_url=self.calculate.metadata['url'], + content=_content, + template_url=self.calculate.metadata["url"], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -99,60 +164,58 @@ async def calculate( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CalculatePriceResponse', pipeline_response) + deserialized = self._deserialize("CalculatePriceResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - calculate.metadata = {'url': "/providers/Microsoft.Capacity/calculatePrice"} # type: ignore - + calculate.metadata = {"url": "/providers/Microsoft.Capacity/calculatePrice"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.ReservationOrderList"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.ReservationOrderResponse"]: """Get all ``ReservationOrder``\ s. List of all the ``ReservationOrder``\ s that the user has access to in the current tenant. - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationOrderList or the result of + :return: An iterator like instance of either ReservationOrderResponse or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationOrderList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderList"] 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( api_version=api_version, - template_url=self.list.metadata['url'], + 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( - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -166,10 +229,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -180,82 +241,93 @@ 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.Capacity/reservationOrders"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders"} # type: ignore async def _purchase_initial( - self, - reservation_order_id: str, - body: "_models.PurchaseRequest", - **kwargs: Any - ) -> "_models.ReservationOrderResponse": - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderResponse"] + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any + ) -> _models.ReservationOrderResponse: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderResponse] - _json = self._serialize.body(body, 'PurchaseRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "PurchaseRequest") - request = build_purchase_request_initial( + request = build_purchase_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._purchase_initial.metadata['url'], + content=_content, + template_url=self._purchase_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _purchase_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore - + _purchase_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore - @distributed_trace_async + @overload async def begin_purchase( self, reservation_order_id: str, - body: "_models.PurchaseRequest", + body: _models.PurchaseRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.ReservationOrderResponse"]: + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: """Purchase ``ReservationOrder``. Purchase ``ReservationOrder`` and create resource under the specified URI. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. + :param body: Information needed for calculate or purchase reservation. Required. :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -268,96 +340,162 @@ async def begin_purchase( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderResponse"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_purchase( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: 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 ReservationOrderResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_purchase( + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Is either a model type + or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ReservationOrderResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderResponse] + 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._purchase_initial( + raw_result = await self._purchase_initial( # type: ignore reservation_order_id=reservation_order_id, body=body, 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('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", 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': 'location'}, **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, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_purchase.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore + begin_purchase.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore @distributed_trace_async async def get( - self, - reservation_order_id: str, - expand: Optional[str] = None, - **kwargs: Any - ) -> "_models.ReservationOrderResponse": + self, reservation_order_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationOrderResponse: """Get a specific ``ReservationOrder``. Get the details of the ``ReservationOrder``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param expand: May be used to expand the planInformation. Default value is None. :type expand: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationOrderResponse, or the result of cls(response) + :return: ReservationOrderResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.ReservationOrderResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderResponse"] 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', "2022-03-01") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderResponse] - request = build_get_request( reservation_order_id=reservation_order_id, - api_version=api_version, expand=expand, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -365,66 +503,126 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore - + get.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore - @distributed_trace_async + @overload async def change_directory( self, reservation_order_id: str, - body: "_models.ChangeDirectoryRequest", + body: _models.ChangeDirectoryRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ChangeDirectoryResponse": + ) -> _models.ChangeDirectoryResponse: """Change directory of ``ReservationOrder``. Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified tenant id. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. + :param body: Information needed to change directory of reservation order. Required. :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ChangeDirectoryResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def change_directory( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: 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: ChangeDirectoryResponse, or the result of cls(response) + :return: ChangeDirectoryResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def change_directory( + self, reservation_order_id: str, body: Union[_models.ChangeDirectoryRequest, IO], **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Is either a model + type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: ChangeDirectoryResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ChangeDirectoryResponse"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - 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(body, 'ChangeDirectoryRequest') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ChangeDirectoryResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ChangeDirectoryRequest") request = build_change_directory_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.change_directory.metadata['url'], + content=_content, + template_url=self.change_directory.metadata["url"], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -432,12 +630,11 @@ async def change_directory( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ChangeDirectoryResponse', pipeline_response) + deserialized = self._deserialize("ChangeDirectoryResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - change_directory.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory"} # type: ignore - + change_directory.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py new file mode 100644 index 000000000000..d9eba33015fe --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py @@ -0,0 +1,179 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._return_operations_operations import build_post_request +from .._vendor import MixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ReturnOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s + :attr:`return_operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def post( + self, + reservation_order_id: str, + body: _models.RefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RefundResponse: + """Return a reservation. + + Return a reservation. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.RefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RefundResponse: + """Return a reservation. + + Return a reservation. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: 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: RefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.RefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def post( + self, reservation_order_id: str, body: Union[_models.RefundRequest, IO], **kwargs: Any + ) -> _models.RefundResponse: + """Return a reservation. + + Return a reservation. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Is either a model type or a IO type. + Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: RefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.RefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RefundResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "RefundRequest") + + request = build_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.post.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("RefundResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py index 2dc65ef71c67..ac1cc9edac36 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py @@ -20,6 +20,9 @@ from ._models_py3 import CalculatePriceResponseProperties from ._models_py3 import CalculatePriceResponsePropertiesBillingCurrencyTotal from ._models_py3 import CalculatePriceResponsePropertiesPricingCurrencyTotal +from ._models_py3 import CalculateRefundRequest +from ._models_py3 import CalculateRefundRequestProperties +from ._models_py3 import CalculateRefundResponse from ._models_py3 import Catalog from ._models_py3 import CatalogMsrp from ._models_py3 import ChangeDirectoryRequest @@ -60,6 +63,14 @@ from ._models_py3 import QuotaRequestProperties from ._models_py3 import QuotaRequestSubmitResponse from ._models_py3 import QuotaRequestSubmitResponse201 +from ._models_py3 import RefundBillingInformation +from ._models_py3 import RefundPolicyError +from ._models_py3 import RefundPolicyResult +from ._models_py3 import RefundPolicyResultProperty +from ._models_py3 import RefundRequest +from ._models_py3 import RefundRequestProperties +from ._models_py3 import RefundResponse +from ._models_py3 import RefundResponseProperties from ._models_py3 import RenewPropertiesResponse from ._models_py3 import RenewPropertiesResponseBillingCurrencyTotal from ._models_py3 import RenewPropertiesResponsePricingCurrencyTotal @@ -93,133 +104,146 @@ from ._models_py3 import SubscriptionScopeProperties from ._models_py3 import SystemData - -from ._azure_reservation_api_enums import ( - AppliedScopeType, - CalculateExchangeOperationResultStatus, - CreatedByType, - DisplayProvisioningState, - ErrorResponseCode, - ExchangeOperationResultStatus, - InstanceFlexibility, - Location, - OperationStatus, - PaymentStatus, - ProvisioningState, - QuotaRequestState, - ReservationBillingPlan, - ReservationStatusCode, - ReservationTerm, - ReservedResourceType, - ResourceType, - UserFriendlyAppliedScopeType, - UserFriendlyRenewState, -) +from ._azure_reservation_api_enums import AppliedScopeType +from ._azure_reservation_api_enums import CalculateExchangeOperationResultStatus +from ._azure_reservation_api_enums import CreatedByType +from ._azure_reservation_api_enums import DisplayProvisioningState +from ._azure_reservation_api_enums import ErrorResponseCode +from ._azure_reservation_api_enums import ExchangeOperationResultStatus +from ._azure_reservation_api_enums import InstanceFlexibility +from ._azure_reservation_api_enums import Location +from ._azure_reservation_api_enums import OperationStatus +from ._azure_reservation_api_enums import PaymentStatus +from ._azure_reservation_api_enums import ProvisioningState +from ._azure_reservation_api_enums import QuotaRequestState +from ._azure_reservation_api_enums import ReservationBillingPlan +from ._azure_reservation_api_enums import ReservationStatusCode +from ._azure_reservation_api_enums import ReservationTerm +from ._azure_reservation_api_enums import ReservedResourceType +from ._azure_reservation_api_enums import ResourceType +from ._azure_reservation_api_enums import UserFriendlyAppliedScopeType +from ._azure_reservation_api_enums import UserFriendlyRenewState +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__ = [ - 'AppliedReservationList', - 'AppliedReservations', - 'AvailableScopeProperties', - 'AvailableScopeRequest', - 'AvailableScopeRequestProperties', - 'BillingInformation', - 'CalculateExchangeOperationResultResponse', - 'CalculateExchangeRequest', - 'CalculateExchangeRequestProperties', - 'CalculateExchangeResponseProperties', - 'CalculatePriceResponse', - 'CalculatePriceResponseProperties', - 'CalculatePriceResponsePropertiesBillingCurrencyTotal', - 'CalculatePriceResponsePropertiesPricingCurrencyTotal', - 'Catalog', - 'CatalogMsrp', - 'ChangeDirectoryRequest', - 'ChangeDirectoryResponse', - 'ChangeDirectoryResult', - 'CreateGenericQuotaRequestParameters', - 'CurrentQuotaLimit', - 'CurrentQuotaLimitBase', - 'Error', - 'ErrorDetails', - 'ErrorResponse', - 'ExceptionResponse', - 'ExchangeOperationResultResponse', - 'ExchangePolicyError', - 'ExchangePolicyErrors', - 'ExchangeRequest', - 'ExchangeRequestProperties', - 'ExchangeResponseProperties', - 'ExtendedErrorInfo', - 'ExtendedStatusInfo', - 'MergeRequest', - 'OperationDisplay', - 'OperationList', - 'OperationResponse', - 'OperationResultError', - 'Patch', - 'PatchPropertiesRenewProperties', - 'PaymentDetail', - 'Price', - 'PurchaseRequest', - 'PurchaseRequestPropertiesReservedResourceProperties', - 'QuotaLimits', - 'QuotaLimitsResponse', - 'QuotaProperties', - 'QuotaRequestDetails', - 'QuotaRequestDetailsList', - 'QuotaRequestOneResourceSubmitResponse', - 'QuotaRequestProperties', - 'QuotaRequestSubmitResponse', - 'QuotaRequestSubmitResponse201', - 'RenewPropertiesResponse', - 'RenewPropertiesResponseBillingCurrencyTotal', - 'RenewPropertiesResponsePricingCurrencyTotal', - 'ReservationList', - 'ReservationMergeProperties', - 'ReservationOrderBillingPlanInformation', - 'ReservationOrderList', - 'ReservationOrderResponse', - 'ReservationResponse', - 'ReservationSplitProperties', - 'ReservationSummary', - 'ReservationToExchange', - 'ReservationToPurchaseCalculateExchange', - 'ReservationToPurchaseExchange', - 'ReservationToReturn', - 'ReservationToReturnForExchange', - 'ReservationUtilizationAggregates', - 'ReservationsListResult', - 'ReservationsProperties', - 'ReservationsPropertiesUtilization', - 'ResourceName', - 'ScopeProperties', - 'ServiceError', - 'ServiceErrorDetail', - 'SkuCapability', - 'SkuName', - 'SkuProperty', - 'SkuRestriction', - 'SplitRequest', - 'SubRequest', - 'SubscriptionScopeProperties', - 'SystemData', - 'AppliedScopeType', - 'CalculateExchangeOperationResultStatus', - 'CreatedByType', - 'DisplayProvisioningState', - 'ErrorResponseCode', - 'ExchangeOperationResultStatus', - 'InstanceFlexibility', - 'Location', - 'OperationStatus', - 'PaymentStatus', - 'ProvisioningState', - 'QuotaRequestState', - 'ReservationBillingPlan', - 'ReservationStatusCode', - 'ReservationTerm', - 'ReservedResourceType', - 'ResourceType', - 'UserFriendlyAppliedScopeType', - 'UserFriendlyRenewState', + "AppliedReservationList", + "AppliedReservations", + "AvailableScopeProperties", + "AvailableScopeRequest", + "AvailableScopeRequestProperties", + "BillingInformation", + "CalculateExchangeOperationResultResponse", + "CalculateExchangeRequest", + "CalculateExchangeRequestProperties", + "CalculateExchangeResponseProperties", + "CalculatePriceResponse", + "CalculatePriceResponseProperties", + "CalculatePriceResponsePropertiesBillingCurrencyTotal", + "CalculatePriceResponsePropertiesPricingCurrencyTotal", + "CalculateRefundRequest", + "CalculateRefundRequestProperties", + "CalculateRefundResponse", + "Catalog", + "CatalogMsrp", + "ChangeDirectoryRequest", + "ChangeDirectoryResponse", + "ChangeDirectoryResult", + "CreateGenericQuotaRequestParameters", + "CurrentQuotaLimit", + "CurrentQuotaLimitBase", + "Error", + "ErrorDetails", + "ErrorResponse", + "ExceptionResponse", + "ExchangeOperationResultResponse", + "ExchangePolicyError", + "ExchangePolicyErrors", + "ExchangeRequest", + "ExchangeRequestProperties", + "ExchangeResponseProperties", + "ExtendedErrorInfo", + "ExtendedStatusInfo", + "MergeRequest", + "OperationDisplay", + "OperationList", + "OperationResponse", + "OperationResultError", + "Patch", + "PatchPropertiesRenewProperties", + "PaymentDetail", + "Price", + "PurchaseRequest", + "PurchaseRequestPropertiesReservedResourceProperties", + "QuotaLimits", + "QuotaLimitsResponse", + "QuotaProperties", + "QuotaRequestDetails", + "QuotaRequestDetailsList", + "QuotaRequestOneResourceSubmitResponse", + "QuotaRequestProperties", + "QuotaRequestSubmitResponse", + "QuotaRequestSubmitResponse201", + "RefundBillingInformation", + "RefundPolicyError", + "RefundPolicyResult", + "RefundPolicyResultProperty", + "RefundRequest", + "RefundRequestProperties", + "RefundResponse", + "RefundResponseProperties", + "RenewPropertiesResponse", + "RenewPropertiesResponseBillingCurrencyTotal", + "RenewPropertiesResponsePricingCurrencyTotal", + "ReservationList", + "ReservationMergeProperties", + "ReservationOrderBillingPlanInformation", + "ReservationOrderList", + "ReservationOrderResponse", + "ReservationResponse", + "ReservationSplitProperties", + "ReservationSummary", + "ReservationToExchange", + "ReservationToPurchaseCalculateExchange", + "ReservationToPurchaseExchange", + "ReservationToReturn", + "ReservationToReturnForExchange", + "ReservationUtilizationAggregates", + "ReservationsListResult", + "ReservationsProperties", + "ReservationsPropertiesUtilization", + "ResourceName", + "ScopeProperties", + "ServiceError", + "ServiceErrorDetail", + "SkuCapability", + "SkuName", + "SkuProperty", + "SkuRestriction", + "SplitRequest", + "SubRequest", + "SubscriptionScopeProperties", + "SystemData", + "AppliedScopeType", + "CalculateExchangeOperationResultStatus", + "CreatedByType", + "DisplayProvisioningState", + "ErrorResponseCode", + "ExchangeOperationResultStatus", + "InstanceFlexibility", + "Location", + "OperationStatus", + "PaymentStatus", + "ProvisioningState", + "QuotaRequestState", + "ReservationBillingPlan", + "ReservationStatusCode", + "ReservationTerm", + "ReservedResourceType", + "ResourceType", + "UserFriendlyAppliedScopeType", + "UserFriendlyRenewState", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_azure_reservation_api_enums.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_azure_reservation_api_enums.py index f65bf9b4e89f..839cd4d2708f 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_azure_reservation_api_enums.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_azure_reservation_api_enums.py @@ -7,38 +7,36 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class AppliedScopeType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Type of the Applied Scope. - """ +class AppliedScopeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the Applied Scope.""" SINGLE = "Single" SHARED = "Shared" -class CalculateExchangeOperationResultStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Status of the operation. - """ + +class CalculateExchangeOperationResultStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the operation.""" SUCCEEDED = "Succeeded" FAILED = "Failed" CANCELLED = "Cancelled" PENDING = "Pending" -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 DisplayProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Represent the current display state of the Reservation. - """ + +class DisplayProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Represent the current display state of the Reservation.""" SUCCEEDED = "Succeeded" EXPIRING = "Expiring" @@ -48,7 +46,9 @@ class DisplayProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum CANCELLED = "Cancelled" FAILED = "Failed" -class ErrorResponseCode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class ErrorResponseCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ErrorResponseCode.""" NOT_SPECIFIED = "NotSpecified" INTERNAL_SERVER_ERROR = "InternalServerError" @@ -106,10 +106,12 @@ class ErrorResponseCode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): FULFILLMENT_ERROR = "FulfillmentError" CALCULATE_PRICE_FAILED = "CalculatePriceFailed" APPLIED_SCOPES_SAME_AS_EXISTING = "AppliedScopesSameAsExisting" + SELF_SERVICE_REFUND_NOT_SUPPORTED = "SelfServiceRefundNotSupported" + REFUND_LIMIT_EXCEEDED = "RefundLimitExceeded" -class ExchangeOperationResultStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Status of the operation. - """ + +class ExchangeOperationResultStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the operation.""" SUCCEEDED = "Succeeded" FAILED = "Failed" @@ -117,7 +119,8 @@ class ExchangeOperationResultStatus(with_metaclass(CaseInsensitiveEnumMeta, str, PENDING_REFUNDS = "PendingRefunds" PENDING_PURCHASES = "PendingPurchases" -class InstanceFlexibility(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class InstanceFlexibility(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Turning this on will apply the reservation discount to other VMs in the same VM size group. Only specify for VirtualMachines reserved resource type. """ @@ -125,7 +128,8 @@ class InstanceFlexibility(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): ON = "On" OFF = "Off" -class Location(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class Location(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Location in which the Resources needs to be reserved. It cannot be changed after the resource has been created. """ @@ -155,27 +159,27 @@ class Location(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): WESTCENTRALUS = "westcentralus" UKWEST = "ukwest" -class OperationStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Status of the individual operation. - """ + +class OperationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the individual operation.""" SUCCEEDED = "Succeeded" FAILED = "Failed" CANCELLED = "Cancelled" PENDING = "Pending" -class PaymentStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Describes whether the payment is completed, failed, cancelled or scheduled in the future. - """ + +class PaymentStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Describes whether the payment is completed, failed, cancelled or scheduled in the future.""" SUCCEEDED = "Succeeded" FAILED = "Failed" SCHEDULED = "Scheduled" CANCELLED = "Cancelled" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Represent the current state of the Reservation. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Represent the current state of the Reservation.""" CREATING = "Creating" PENDING_RESOURCE_HOLD = "PendingResourceHold" @@ -191,9 +195,9 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): SPLIT = "Split" MERGED = "Merged" -class QuotaRequestState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The quota request status. - """ + +class QuotaRequestState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The quota request status.""" ACCEPTED = "Accepted" INVALID = "Invalid" @@ -201,14 +205,16 @@ class QuotaRequestState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): FAILED = "Failed" IN_PROGRESS = "InProgress" -class ReservationBillingPlan(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Represent the billing plans. - """ + +class ReservationBillingPlan(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Represent the billing plans.""" UPFRONT = "Upfront" MONTHLY = "Monthly" -class ReservationStatusCode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class ReservationStatusCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ReservationStatusCode.""" NONE = "None" PENDING = "Pending" @@ -221,17 +227,17 @@ class ReservationStatusCode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): EXPIRED = "Expired" SUCCEEDED = "Succeeded" -class ReservationTerm(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Represent the term of Reservation. - """ + +class ReservationTerm(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Represent the term of Reservation.""" P1_Y = "P1Y" P3_Y = "P3Y" P5_Y = "P5Y" -class ReservedResourceType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of the resource that is being reserved. - """ + +class ReservedResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the resource that is being reserved.""" VIRTUAL_MACHINES = "VirtualMachines" SQL_DATABASES = "SqlDatabases" @@ -260,9 +266,9 @@ class ReservedResourceType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): SQL_EDGE = "SqlEdge" VIRTUAL_MACHINE_SOFTWARE = "VirtualMachineSoftware" -class ResourceType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The resource types. - """ + +class ResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The resource types.""" STANDARD = "standard" DEDICATED = "dedicated" @@ -270,9 +276,9 @@ class ResourceType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): SHARED = "shared" SERVICE_SPECIFIC = "serviceSpecific" -class UserFriendlyAppliedScopeType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The applied scope type - """ + +class UserFriendlyAppliedScopeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The applied scope type.""" NONE = "None" SHARED = "Shared" @@ -280,9 +286,9 @@ class UserFriendlyAppliedScopeType(with_metaclass(CaseInsensitiveEnumMeta, str, RESOURCE_GROUP = "ResourceGroup" MANAGEMENT_GROUP = "ManagementGroup" -class UserFriendlyRenewState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The renew state of the reservation - """ + +class UserFriendlyRenewState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The renew state of the reservation.""" ON = "On" OFF = "Off" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models_py3.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models_py3.py index a8d9b0340f1d..90725a0fddfb 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models_py3.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/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,22 @@ # -------------------------------------------------------------------------- import datetime -from typing import Any, Dict, List, Optional, Union +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._azure_reservation_api_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class AppliedReservationList(msrest.serialization.Model): +class AppliedReservationList(_serialization.Model): """AppliedReservationList. :ivar value: @@ -25,29 +33,23 @@ class AppliedReservationList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[str]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[str]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List[str]] = None, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List[str]] = None, next_link: Optional[str] = None, **kwargs): """ :keyword value: :paramtype value: list[str] :keyword next_link: Url to get the next page of reservations. :paramtype next_link: str """ - super(AppliedReservationList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class AppliedReservations(msrest.serialization.Model): +class AppliedReservations(_serialization.Model): """AppliedReservations. Variables are only populated by the server, and will be ignored when sending a request. @@ -63,36 +65,31 @@ class AppliedReservations(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'}, - 'reservation_order_ids': {'key': 'properties.reservationOrderIds', 'type': 'AppliedReservationList'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "reservation_order_ids": {"key": "properties.reservationOrderIds", "type": "AppliedReservationList"}, } - def __init__( - self, - *, - reservation_order_ids: Optional["AppliedReservationList"] = None, - **kwargs - ): + def __init__(self, *, reservation_order_ids: Optional["_models.AppliedReservationList"] = None, **kwargs): """ :keyword reservation_order_ids: :paramtype reservation_order_ids: ~azure.mgmt.reservations.models.AppliedReservationList """ - super(AppliedReservations, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.type = None self.reservation_order_ids = reservation_order_ids -class AvailableScopeProperties(msrest.serialization.Model): +class AvailableScopeProperties(_serialization.Model): """AvailableScopeProperties. :ivar properties: @@ -100,24 +97,19 @@ class AvailableScopeProperties(msrest.serialization.Model): """ _attribute_map = { - 'properties': {'key': 'properties', 'type': 'SubscriptionScopeProperties'}, + "properties": {"key": "properties", "type": "SubscriptionScopeProperties"}, } - def __init__( - self, - *, - properties: Optional["SubscriptionScopeProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.SubscriptionScopeProperties"] = None, **kwargs): """ :keyword properties: :paramtype properties: ~azure.mgmt.reservations.models.SubscriptionScopeProperties """ - super(AvailableScopeProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties -class AvailableScopeRequest(msrest.serialization.Model): +class AvailableScopeRequest(_serialization.Model): """Available scope. :ivar properties: Available scope request properties. @@ -125,24 +117,19 @@ class AvailableScopeRequest(msrest.serialization.Model): """ _attribute_map = { - 'properties': {'key': 'properties', 'type': 'AvailableScopeRequestProperties'}, + "properties": {"key": "properties", "type": "AvailableScopeRequestProperties"}, } - def __init__( - self, - *, - properties: Optional["AvailableScopeRequestProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.AvailableScopeRequestProperties"] = None, **kwargs): """ :keyword properties: Available scope request properties. :paramtype properties: ~azure.mgmt.reservations.models.AvailableScopeRequestProperties """ - super(AvailableScopeRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties -class AvailableScopeRequestProperties(msrest.serialization.Model): +class AvailableScopeRequestProperties(_serialization.Model): """Available scope request properties. :ivar scopes: @@ -150,24 +137,19 @@ class AvailableScopeRequestProperties(msrest.serialization.Model): """ _attribute_map = { - 'scopes': {'key': 'scopes', 'type': '[str]'}, + "scopes": {"key": "scopes", "type": "[str]"}, } - def __init__( - self, - *, - scopes: Optional[List[str]] = None, - **kwargs - ): + def __init__(self, *, scopes: Optional[List[str]] = None, **kwargs): """ :keyword scopes: :paramtype scopes: list[str] """ - super(AvailableScopeRequestProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.scopes = scopes -class BillingInformation(msrest.serialization.Model): +class BillingInformation(_serialization.Model): """billing information. :ivar billing_currency_total_paid_amount: @@ -179,17 +161,20 @@ class BillingInformation(msrest.serialization.Model): """ _attribute_map = { - 'billing_currency_total_paid_amount': {'key': 'billingCurrencyTotalPaidAmount', 'type': 'Price'}, - 'billing_currency_prorated_amount': {'key': 'billingCurrencyProratedAmount', 'type': 'Price'}, - 'billing_currency_remaining_commitment_amount': {'key': 'billingCurrencyRemainingCommitmentAmount', 'type': 'Price'}, + "billing_currency_total_paid_amount": {"key": "billingCurrencyTotalPaidAmount", "type": "Price"}, + "billing_currency_prorated_amount": {"key": "billingCurrencyProratedAmount", "type": "Price"}, + "billing_currency_remaining_commitment_amount": { + "key": "billingCurrencyRemainingCommitmentAmount", + "type": "Price", + }, } def __init__( self, *, - billing_currency_total_paid_amount: Optional["Price"] = None, - billing_currency_prorated_amount: Optional["Price"] = None, - billing_currency_remaining_commitment_amount: Optional["Price"] = None, + billing_currency_total_paid_amount: Optional["_models.Price"] = None, + billing_currency_prorated_amount: Optional["_models.Price"] = None, + billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None, **kwargs ): """ @@ -200,13 +185,13 @@ def __init__( :keyword billing_currency_remaining_commitment_amount: :paramtype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price """ - super(BillingInformation, self).__init__(**kwargs) + super().__init__(**kwargs) self.billing_currency_total_paid_amount = billing_currency_total_paid_amount self.billing_currency_prorated_amount = billing_currency_prorated_amount self.billing_currency_remaining_commitment_amount = billing_currency_remaining_commitment_amount -class CalculateExchangeOperationResultResponse(msrest.serialization.Model): +class CalculateExchangeOperationResultResponse(_serialization.Model): """CalculateExchange operation result. :ivar id: It should match what is used to GET the operation result. @@ -214,8 +199,8 @@ class CalculateExchangeOperationResultResponse(msrest.serialization.Model): :ivar name: It must match the last segment of the id field, and will typically be a GUID / system generated value. :vartype name: str - :ivar status: Status of the operation. Possible values include: "Succeeded", "Failed", - "Cancelled", "Pending". + :ivar status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", + and "Pending". :vartype status: str or ~azure.mgmt.reservations.models.CalculateExchangeOperationResultStatus :ivar properties: CalculateExchange response properties. :vartype properties: ~azure.mgmt.reservations.models.CalculateExchangeResponseProperties @@ -224,21 +209,21 @@ class CalculateExchangeOperationResultResponse(msrest.serialization.Model): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'CalculateExchangeResponseProperties'}, - 'error': {'key': 'error', 'type': 'OperationResultError'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "properties": {"key": "properties", "type": "CalculateExchangeResponseProperties"}, + "error": {"key": "error", "type": "OperationResultError"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, - status: Optional[Union[str, "CalculateExchangeOperationResultStatus"]] = None, - properties: Optional["CalculateExchangeResponseProperties"] = None, - error: Optional["OperationResultError"] = None, + status: Optional[Union[str, "_models.CalculateExchangeOperationResultStatus"]] = None, + properties: Optional["_models.CalculateExchangeResponseProperties"] = None, + error: Optional["_models.OperationResultError"] = None, **kwargs ): """ @@ -247,8 +232,8 @@ def __init__( :keyword name: It must match the last segment of the id field, and will typically be a GUID / system generated value. :paramtype name: str - :keyword status: Status of the operation. Possible values include: "Succeeded", "Failed", - "Cancelled", "Pending". + :keyword status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", + and "Pending". :paramtype status: str or ~azure.mgmt.reservations.models.CalculateExchangeOperationResultStatus :keyword properties: CalculateExchange response properties. @@ -256,7 +241,7 @@ def __init__( :keyword error: Required if status == failed or status == canceled. :paramtype error: ~azure.mgmt.reservations.models.OperationResultError """ - super(CalculateExchangeOperationResultResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.name = name self.status = status @@ -264,7 +249,7 @@ def __init__( self.error = error -class CalculateExchangeRequest(msrest.serialization.Model): +class CalculateExchangeRequest(_serialization.Model): """Calculate exchange request. :ivar properties: Calculate exchange request properties. @@ -272,24 +257,19 @@ class CalculateExchangeRequest(msrest.serialization.Model): """ _attribute_map = { - 'properties': {'key': 'properties', 'type': 'CalculateExchangeRequestProperties'}, + "properties": {"key": "properties", "type": "CalculateExchangeRequestProperties"}, } - def __init__( - self, - *, - properties: Optional["CalculateExchangeRequestProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.CalculateExchangeRequestProperties"] = None, **kwargs): """ :keyword properties: Calculate exchange request properties. :paramtype properties: ~azure.mgmt.reservations.models.CalculateExchangeRequestProperties """ - super(CalculateExchangeRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties -class CalculateExchangeRequestProperties(msrest.serialization.Model): +class CalculateExchangeRequestProperties(_serialization.Model): """Calculate exchange request properties. :ivar reservations_to_purchase: List of reservations that are being purchased in this exchange. @@ -299,15 +279,15 @@ class CalculateExchangeRequestProperties(msrest.serialization.Model): """ _attribute_map = { - 'reservations_to_purchase': {'key': 'reservationsToPurchase', 'type': '[PurchaseRequest]'}, - 'reservations_to_exchange': {'key': 'reservationsToExchange', 'type': '[ReservationToReturn]'}, + "reservations_to_purchase": {"key": "reservationsToPurchase", "type": "[PurchaseRequest]"}, + "reservations_to_exchange": {"key": "reservationsToExchange", "type": "[ReservationToReturn]"}, } def __init__( self, *, - reservations_to_purchase: Optional[List["PurchaseRequest"]] = None, - reservations_to_exchange: Optional[List["ReservationToReturn"]] = None, + reservations_to_purchase: Optional[List["_models.PurchaseRequest"]] = None, + reservations_to_exchange: Optional[List["_models.ReservationToReturn"]] = None, **kwargs ): """ @@ -318,12 +298,12 @@ def __init__( exchange. :paramtype reservations_to_exchange: list[~azure.mgmt.reservations.models.ReservationToReturn] """ - super(CalculateExchangeRequestProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.reservations_to_purchase = reservations_to_purchase self.reservations_to_exchange = reservations_to_exchange -class CalculateExchangeResponseProperties(msrest.serialization.Model): +class CalculateExchangeResponseProperties(_serialization.Model): """CalculateExchange response properties. :ivar session_id: Exchange session identifier. @@ -344,25 +324,28 @@ class CalculateExchangeResponseProperties(msrest.serialization.Model): """ _attribute_map = { - 'session_id': {'key': 'sessionId', 'type': 'str'}, - 'net_payable': {'key': 'netPayable', 'type': 'Price'}, - 'refunds_total': {'key': 'refundsTotal', 'type': 'Price'}, - 'purchases_total': {'key': 'purchasesTotal', 'type': 'Price'}, - 'reservations_to_purchase': {'key': 'reservationsToPurchase', 'type': '[ReservationToPurchaseCalculateExchange]'}, - 'reservations_to_exchange': {'key': 'reservationsToExchange', 'type': '[ReservationToExchange]'}, - 'policy_result': {'key': 'policyResult', 'type': 'ExchangePolicyErrors'}, + "session_id": {"key": "sessionId", "type": "str"}, + "net_payable": {"key": "netPayable", "type": "Price"}, + "refunds_total": {"key": "refundsTotal", "type": "Price"}, + "purchases_total": {"key": "purchasesTotal", "type": "Price"}, + "reservations_to_purchase": { + "key": "reservationsToPurchase", + "type": "[ReservationToPurchaseCalculateExchange]", + }, + "reservations_to_exchange": {"key": "reservationsToExchange", "type": "[ReservationToExchange]"}, + "policy_result": {"key": "policyResult", "type": "ExchangePolicyErrors"}, } def __init__( self, *, session_id: Optional[str] = None, - net_payable: Optional["Price"] = None, - refunds_total: Optional["Price"] = None, - purchases_total: Optional["Price"] = None, - reservations_to_purchase: Optional[List["ReservationToPurchaseCalculateExchange"]] = None, - reservations_to_exchange: Optional[List["ReservationToExchange"]] = None, - policy_result: Optional["ExchangePolicyErrors"] = None, + net_payable: Optional["_models.Price"] = None, + refunds_total: Optional["_models.Price"] = None, + purchases_total: Optional["_models.Price"] = None, + reservations_to_purchase: Optional[List["_models.ReservationToPurchaseCalculateExchange"]] = None, + reservations_to_exchange: Optional[List["_models.ReservationToExchange"]] = None, + policy_result: Optional["_models.ExchangePolicyErrors"] = None, **kwargs ): """ @@ -383,7 +366,7 @@ def __init__( :keyword policy_result: Exchange policy errors. :paramtype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors """ - super(CalculateExchangeResponseProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.session_id = session_id self.net_payable = net_payable self.refunds_total = refunds_total @@ -393,7 +376,7 @@ def __init__( self.policy_result = policy_result -class CalculatePriceResponse(msrest.serialization.Model): +class CalculatePriceResponse(_serialization.Model): """CalculatePriceResponse. :ivar properties: @@ -401,24 +384,19 @@ class CalculatePriceResponse(msrest.serialization.Model): """ _attribute_map = { - 'properties': {'key': 'properties', 'type': 'CalculatePriceResponseProperties'}, + "properties": {"key": "properties", "type": "CalculatePriceResponseProperties"}, } - def __init__( - self, - *, - properties: Optional["CalculatePriceResponseProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.CalculatePriceResponseProperties"] = None, **kwargs): """ :keyword properties: :paramtype properties: ~azure.mgmt.reservations.models.CalculatePriceResponseProperties """ - super(CalculatePriceResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties -class CalculatePriceResponseProperties(msrest.serialization.Model): +class CalculatePriceResponseProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """CalculatePriceResponseProperties. :ivar billing_currency_total: Currency and amount that customer will be charged in customer's @@ -452,23 +430,29 @@ class CalculatePriceResponseProperties(msrest.serialization.Model): """ _attribute_map = { - 'billing_currency_total': {'key': 'billingCurrencyTotal', 'type': 'CalculatePriceResponsePropertiesBillingCurrencyTotal'}, - 'net_total': {'key': 'netTotal', 'type': 'float'}, - 'tax_total': {'key': 'taxTotal', 'type': 'float'}, - 'grand_total': {'key': 'grandTotal', 'type': 'float'}, - 'is_tax_included': {'key': 'isTaxIncluded', 'type': 'bool'}, - 'is_billing_partner_managed': {'key': 'isBillingPartnerManaged', 'type': 'bool'}, - 'reservation_order_id': {'key': 'reservationOrderId', 'type': 'str'}, - 'sku_title': {'key': 'skuTitle', 'type': 'str'}, - 'sku_description': {'key': 'skuDescription', 'type': 'str'}, - 'pricing_currency_total': {'key': 'pricingCurrencyTotal', 'type': 'CalculatePriceResponsePropertiesPricingCurrencyTotal'}, - 'payment_schedule': {'key': 'paymentSchedule', 'type': '[PaymentDetail]'}, + "billing_currency_total": { + "key": "billingCurrencyTotal", + "type": "CalculatePriceResponsePropertiesBillingCurrencyTotal", + }, + "net_total": {"key": "netTotal", "type": "float"}, + "tax_total": {"key": "taxTotal", "type": "float"}, + "grand_total": {"key": "grandTotal", "type": "float"}, + "is_tax_included": {"key": "isTaxIncluded", "type": "bool"}, + "is_billing_partner_managed": {"key": "isBillingPartnerManaged", "type": "bool"}, + "reservation_order_id": {"key": "reservationOrderId", "type": "str"}, + "sku_title": {"key": "skuTitle", "type": "str"}, + "sku_description": {"key": "skuDescription", "type": "str"}, + "pricing_currency_total": { + "key": "pricingCurrencyTotal", + "type": "CalculatePriceResponsePropertiesPricingCurrencyTotal", + }, + "payment_schedule": {"key": "paymentSchedule", "type": "[PaymentDetail]"}, } def __init__( self, *, - billing_currency_total: Optional["CalculatePriceResponsePropertiesBillingCurrencyTotal"] = None, + billing_currency_total: Optional["_models.CalculatePriceResponsePropertiesBillingCurrencyTotal"] = None, net_total: Optional[float] = None, tax_total: Optional[float] = None, grand_total: Optional[float] = None, @@ -477,8 +461,8 @@ def __init__( reservation_order_id: Optional[str] = None, sku_title: Optional[str] = None, sku_description: Optional[str] = None, - pricing_currency_total: Optional["CalculatePriceResponsePropertiesPricingCurrencyTotal"] = None, - payment_schedule: Optional[List["PaymentDetail"]] = None, + pricing_currency_total: Optional["_models.CalculatePriceResponsePropertiesPricingCurrencyTotal"] = None, + payment_schedule: Optional[List["_models.PaymentDetail"]] = None, **kwargs ): """ @@ -511,7 +495,7 @@ def __init__( :keyword payment_schedule: :paramtype payment_schedule: list[~azure.mgmt.reservations.models.PaymentDetail] """ - super(CalculatePriceResponseProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.billing_currency_total = billing_currency_total self.net_total = net_total self.tax_total = tax_total @@ -525,7 +509,7 @@ def __init__( self.payment_schedule = payment_schedule -class CalculatePriceResponsePropertiesBillingCurrencyTotal(msrest.serialization.Model): +class CalculatePriceResponsePropertiesBillingCurrencyTotal(_serialization.Model): """Currency and amount that customer will be charged in customer's local currency. Tax is not included. :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase @@ -536,17 +520,11 @@ class CalculatePriceResponsePropertiesBillingCurrencyTotal(msrest.serialization. """ _attribute_map = { - 'currency_code': {'key': 'currencyCode', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "amount": {"key": "amount", "type": "float"}, } - def __init__( - self, - *, - currency_code: Optional[str] = None, - amount: Optional[float] = None, - **kwargs - ): + def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs): """ :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase record. @@ -554,12 +532,12 @@ def __init__( :keyword amount: Amount in pricing currency. Tax is not included. :paramtype amount: float """ - super(CalculatePriceResponsePropertiesBillingCurrencyTotal, self).__init__(**kwargs) + super().__init__(**kwargs) self.currency_code = currency_code self.amount = amount -class CalculatePriceResponsePropertiesPricingCurrencyTotal(msrest.serialization.Model): +class CalculatePriceResponsePropertiesPricingCurrencyTotal(_serialization.Model): """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is not included. :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase @@ -570,17 +548,11 @@ class CalculatePriceResponsePropertiesPricingCurrencyTotal(msrest.serialization. """ _attribute_map = { - 'currency_code': {'key': 'currencyCode', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "amount": {"key": "amount", "type": "float"}, } - def __init__( - self, - *, - currency_code: Optional[str] = None, - amount: Optional[float] = None, - **kwargs - ): + def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs): """ :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase record. @@ -588,12 +560,108 @@ def __init__( :keyword amount: :paramtype amount: float """ - super(CalculatePriceResponsePropertiesPricingCurrencyTotal, self).__init__(**kwargs) + super().__init__(**kwargs) self.currency_code = currency_code self.amount = amount -class Catalog(msrest.serialization.Model): +class CalculateRefundRequest(_serialization.Model): + """CalculateRefundRequest. + + :ivar id: Fully qualified identifier of the reservation order being returned. + :vartype id: str + :ivar properties: + :vartype properties: ~azure.mgmt.reservations.models.CalculateRefundRequestProperties + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "properties": {"key": "properties", "type": "CalculateRefundRequestProperties"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + properties: Optional["_models.CalculateRefundRequestProperties"] = None, + **kwargs + ): + """ + :keyword id: Fully qualified identifier of the reservation order being returned. + :paramtype id: str + :keyword properties: + :paramtype properties: ~azure.mgmt.reservations.models.CalculateRefundRequestProperties + """ + super().__init__(**kwargs) + self.id = id + self.properties = properties + + +class CalculateRefundRequestProperties(_serialization.Model): + """CalculateRefundRequestProperties. + + :ivar scope: The scope of the refund, e.g. Reservation. + :vartype scope: str + :ivar reservation_to_return: Reservation to return. + :vartype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn + """ + + _attribute_map = { + "scope": {"key": "scope", "type": "str"}, + "reservation_to_return": {"key": "reservationToReturn", "type": "ReservationToReturn"}, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + reservation_to_return: Optional["_models.ReservationToReturn"] = None, + **kwargs + ): + """ + :keyword scope: The scope of the refund, e.g. Reservation. + :paramtype scope: str + :keyword reservation_to_return: Reservation to return. + :paramtype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn + """ + super().__init__(**kwargs) + self.scope = scope + self.reservation_to_return = reservation_to_return + + +class CalculateRefundResponse(_serialization.Model): + """CalculateRefundResponse. + + :ivar id: Fully qualified identifier of the reservation being returned. + :vartype id: str + :ivar properties: + :vartype properties: ~azure.mgmt.reservations.models.RefundResponseProperties + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "properties": {"key": "properties", "type": "RefundResponseProperties"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + properties: Optional["_models.RefundResponseProperties"] = None, + **kwargs + ): + """ + :keyword id: Fully qualified identifier of the reservation being returned. + :paramtype id: str + :keyword properties: + :paramtype properties: ~azure.mgmt.reservations.models.RefundResponseProperties + """ + super().__init__(**kwargs) + self.id = id + self.properties = properties + + +class Catalog(_serialization.Model): # pylint: disable=too-many-instance-attributes """Catalog. Variables are only populated by the server, and will be ignored when sending a request. @@ -624,44 +692,41 @@ class Catalog(msrest.serialization.Model): """ _validation = { - 'resource_type': {'readonly': True}, - 'name': {'readonly': True}, - 'terms': {'readonly': True}, - 'locations': {'readonly': True}, - 'sku_properties': {'readonly': True}, - 'msrp': {'readonly': True}, - 'restrictions': {'readonly': True}, - 'tier': {'readonly': True}, - 'size': {'readonly': True}, - 'capabilities': {'readonly': True}, - } - - _attribute_map = { - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'billing_plans': {'key': 'billingPlans', 'type': '{[str]}'}, - 'terms': {'key': 'terms', 'type': '[str]'}, - 'locations': {'key': 'locations', 'type': '[str]'}, - 'sku_properties': {'key': 'skuProperties', 'type': '[SkuProperty]'}, - 'msrp': {'key': 'msrp', 'type': 'CatalogMsrp'}, - 'restrictions': {'key': 'restrictions', 'type': '[SkuRestriction]'}, - 'tier': {'key': 'tier', 'type': 'str'}, - 'size': {'key': 'size', 'type': 'str'}, - 'capabilities': {'key': 'capabilities', 'type': '[SkuCapability]'}, + "resource_type": {"readonly": True}, + "name": {"readonly": True}, + "terms": {"readonly": True}, + "locations": {"readonly": True}, + "sku_properties": {"readonly": True}, + "msrp": {"readonly": True}, + "restrictions": {"readonly": True}, + "tier": {"readonly": True}, + "size": {"readonly": True}, + "capabilities": {"readonly": True}, + } + + _attribute_map = { + "resource_type": {"key": "resourceType", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "billing_plans": {"key": "billingPlans", "type": "{[str]}"}, + "terms": {"key": "terms", "type": "[str]"}, + "locations": {"key": "locations", "type": "[str]"}, + "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "msrp": {"key": "msrp", "type": "CatalogMsrp"}, + "restrictions": {"key": "restrictions", "type": "[SkuRestriction]"}, + "tier": {"key": "tier", "type": "str"}, + "size": {"key": "size", "type": "str"}, + "capabilities": {"key": "capabilities", "type": "[SkuCapability]"}, } def __init__( - self, - *, - billing_plans: Optional[Dict[str, List[Union[str, "ReservationBillingPlan"]]]] = None, - **kwargs + self, *, billing_plans: Optional[Dict[str, List[Union[str, "_models.ReservationBillingPlan"]]]] = None, **kwargs ): """ :keyword billing_plans: The billing plan options available for this SKU. :paramtype billing_plans: dict[str, list[str or ~azure.mgmt.reservations.models.ReservationBillingPlan]] """ - super(Catalog, self).__init__(**kwargs) + super().__init__(**kwargs) self.resource_type = None self.name = None self.billing_plans = billing_plans @@ -675,7 +740,7 @@ def __init__( self.capabilities = None -class CatalogMsrp(msrest.serialization.Model): +class CatalogMsrp(_serialization.Model): """Pricing information about the SKU. :ivar p1_y: Amount in pricing currency. Tax not included. @@ -683,24 +748,19 @@ class CatalogMsrp(msrest.serialization.Model): """ _attribute_map = { - 'p1_y': {'key': 'p1Y', 'type': 'Price'}, + "p1_y": {"key": "p1Y", "type": "Price"}, } - def __init__( - self, - *, - p1_y: Optional["Price"] = None, - **kwargs - ): + def __init__(self, *, p1_y: Optional["_models.Price"] = None, **kwargs): """ :keyword p1_y: Amount in pricing currency. Tax not included. :paramtype p1_y: ~azure.mgmt.reservations.models.Price """ - super(CatalogMsrp, self).__init__(**kwargs) + super().__init__(**kwargs) self.p1_y = p1_y -class ChangeDirectoryRequest(msrest.serialization.Model): +class ChangeDirectoryRequest(_serialization.Model): """ChangeDirectoryRequest. :ivar destination_tenant_id: Tenant id GUID that reservation order is to be transferred to. @@ -708,24 +768,19 @@ class ChangeDirectoryRequest(msrest.serialization.Model): """ _attribute_map = { - 'destination_tenant_id': {'key': 'destinationTenantId', 'type': 'str'}, + "destination_tenant_id": {"key": "destinationTenantId", "type": "str"}, } - def __init__( - self, - *, - destination_tenant_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, destination_tenant_id: Optional[str] = None, **kwargs): """ :keyword destination_tenant_id: Tenant id GUID that reservation order is to be transferred to. :paramtype destination_tenant_id: str """ - super(ChangeDirectoryRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.destination_tenant_id = destination_tenant_id -class ChangeDirectoryResponse(msrest.serialization.Model): +class ChangeDirectoryResponse(_serialization.Model): """Change directory response. :ivar reservation_order: Change directory result for reservation order or reservation. @@ -735,15 +790,15 @@ class ChangeDirectoryResponse(msrest.serialization.Model): """ _attribute_map = { - 'reservation_order': {'key': 'reservationOrder', 'type': 'ChangeDirectoryResult'}, - 'reservations': {'key': 'reservations', 'type': '[ChangeDirectoryResult]'}, + "reservation_order": {"key": "reservationOrder", "type": "ChangeDirectoryResult"}, + "reservations": {"key": "reservations", "type": "[ChangeDirectoryResult]"}, } def __init__( self, *, - reservation_order: Optional["ChangeDirectoryResult"] = None, - reservations: Optional[List["ChangeDirectoryResult"]] = None, + reservation_order: Optional["_models.ChangeDirectoryResult"] = None, + reservations: Optional[List["_models.ChangeDirectoryResult"]] = None, **kwargs ): """ @@ -752,12 +807,12 @@ def __init__( :keyword reservations: :paramtype reservations: list[~azure.mgmt.reservations.models.ChangeDirectoryResult] """ - super(ChangeDirectoryResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.reservation_order = reservation_order self.reservations = reservations -class ChangeDirectoryResult(msrest.serialization.Model): +class ChangeDirectoryResult(_serialization.Model): """Change directory result for reservation order or reservation. :ivar id: Identifier of the reservation order or reservation. @@ -772,16 +827,16 @@ class ChangeDirectoryResult(msrest.serialization.Model): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'is_succeeded': {'key': 'isSucceeded', 'type': 'bool'}, - 'error': {'key': 'error', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "is_succeeded": {"key": "isSucceeded", "type": "bool"}, + "error": {"key": "error", "type": "str"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, is_succeeded: Optional[bool] = None, error: Optional[str] = None, @@ -798,14 +853,14 @@ def __init__( :keyword error: Error reason if operation failed. Null otherwise. :paramtype error: str """ - super(ChangeDirectoryResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.name = name self.is_succeeded = is_succeeded self.error = error -class CreateGenericQuotaRequestParameters(msrest.serialization.Model): +class CreateGenericQuotaRequestParameters(_serialization.Model): """Quota change requests information. :ivar value: Quota change requests. @@ -813,30 +868,25 @@ class CreateGenericQuotaRequestParameters(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[CurrentQuotaLimitBase]'}, + "value": {"key": "value", "type": "[CurrentQuotaLimitBase]"}, } - def __init__( - self, - *, - value: Optional[List["CurrentQuotaLimitBase"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.CurrentQuotaLimitBase"]] = None, **kwargs): """ :keyword value: Quota change requests. :paramtype value: list[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] """ - super(CreateGenericQuotaRequestParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class CurrentQuotaLimit(msrest.serialization.Model): +class CurrentQuotaLimit(_serialization.Model): """Current quota limits. Variables are only populated by the server, and will be ignored when sending a request. - :ivar provisioning_state: The details of the quota request status. Possible values include: - "Accepted", "Invalid", "Succeeded", "Failed", "InProgress". + :ivar provisioning_state: The details of the quota request status. Known values are: + "Accepted", "Invalid", "Succeeded", "Failed", and "InProgress". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :ivar message: A user friendly message. :vartype message: str @@ -851,33 +901,28 @@ class CurrentQuotaLimit(msrest.serialization.Model): """ _validation = { - 'provisioning_state': {'readonly': True}, - 'message': {'readonly': True}, - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "provisioning_state": {"readonly": True}, + "message": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'message': {'key': 'properties.message', 'type': 'str'}, - 'id': {'key': 'quotaInformation.id', 'type': 'str'}, - 'name': {'key': 'quotaInformation.name', 'type': 'str'}, - 'type': {'key': 'quotaInformation.type', 'type': 'str'}, - 'properties': {'key': 'quotaInformation.properties', 'type': 'QuotaProperties'}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "message": {"key": "properties.message", "type": "str"}, + "id": {"key": "quotaInformation.id", "type": "str"}, + "name": {"key": "quotaInformation.name", "type": "str"}, + "type": {"key": "quotaInformation.type", "type": "str"}, + "properties": {"key": "quotaInformation.properties", "type": "QuotaProperties"}, } - def __init__( - self, - *, - properties: Optional["QuotaProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.QuotaProperties"] = None, **kwargs): """ :keyword properties: Quota properties for the resource. :paramtype properties: ~azure.mgmt.reservations.models.QuotaProperties """ - super(CurrentQuotaLimit, self).__init__(**kwargs) + super().__init__(**kwargs) self.provisioning_state = None self.message = None self.id = None @@ -886,7 +931,7 @@ def __init__( self.properties = properties -class CurrentQuotaLimitBase(msrest.serialization.Model): +class CurrentQuotaLimitBase(_serialization.Model): """Quota properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -902,36 +947,31 @@ class CurrentQuotaLimitBase(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'}, - 'properties': {'key': 'properties', 'type': 'QuotaProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "QuotaProperties"}, } - def __init__( - self, - *, - properties: Optional["QuotaProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.QuotaProperties"] = None, **kwargs): """ :keyword properties: Quota properties for the resource. :paramtype properties: ~azure.mgmt.reservations.models.QuotaProperties """ - super(CurrentQuotaLimitBase, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.type = None self.properties = properties -class Error(msrest.serialization.Model): +class Error(_serialization.Model): """Error. :ivar error: @@ -939,24 +979,19 @@ class Error(msrest.serialization.Model): """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ExtendedErrorInfo'}, + "error": {"key": "error", "type": "ExtendedErrorInfo"}, } - def __init__( - self, - *, - error: Optional["ExtendedErrorInfo"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ExtendedErrorInfo"] = None, **kwargs): """ :keyword error: :paramtype error: ~azure.mgmt.reservations.models.ExtendedErrorInfo """ - super(Error, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error -class ErrorDetails(msrest.serialization.Model): +class ErrorDetails(_serialization.Model): """The details of the error. Variables are only populated by the server, and will be ignored when sending a request. @@ -970,30 +1005,26 @@ class ErrorDetails(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorDetails, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. :ivar error: The details of the error. @@ -1001,24 +1032,19 @@ class ErrorResponse(msrest.serialization.Model): """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, + "error": {"key": "error", "type": "ErrorDetails"}, } - def __init__( - self, - *, - error: Optional["ErrorDetails"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.reservations.models.ErrorDetails """ - super(ErrorResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error -class ExceptionResponse(msrest.serialization.Model): +class ExceptionResponse(_serialization.Model): """The API error. :ivar error: The API error details. @@ -1026,24 +1052,19 @@ class ExceptionResponse(msrest.serialization.Model): """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ServiceError'}, + "error": {"key": "error", "type": "ServiceError"}, } - def __init__( - self, - *, - error: Optional["ServiceError"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ServiceError"] = None, **kwargs): """ :keyword error: The API error details. :paramtype error: ~azure.mgmt.reservations.models.ServiceError """ - super(ExceptionResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error -class ExchangeOperationResultResponse(msrest.serialization.Model): +class ExchangeOperationResultResponse(_serialization.Model): """Exchange operation result. :ivar id: It should match what is used to GET the operation result. @@ -1051,8 +1072,8 @@ class ExchangeOperationResultResponse(msrest.serialization.Model): :ivar name: It must match the last segment of the id field, and will typically be a GUID / system generated value. :vartype name: str - :ivar status: Status of the operation. Possible values include: "Succeeded", "Failed", - "Cancelled", "PendingRefunds", "PendingPurchases". + :ivar status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", + "PendingRefunds", and "PendingPurchases". :vartype status: str or ~azure.mgmt.reservations.models.ExchangeOperationResultStatus :ivar properties: Exchange response properties. :vartype properties: ~azure.mgmt.reservations.models.ExchangeResponseProperties @@ -1061,21 +1082,21 @@ class ExchangeOperationResultResponse(msrest.serialization.Model): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'ExchangeResponseProperties'}, - 'error': {'key': 'error', 'type': 'OperationResultError'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "properties": {"key": "properties", "type": "ExchangeResponseProperties"}, + "error": {"key": "error", "type": "OperationResultError"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, - status: Optional[Union[str, "ExchangeOperationResultStatus"]] = None, - properties: Optional["ExchangeResponseProperties"] = None, - error: Optional["OperationResultError"] = None, + status: Optional[Union[str, "_models.ExchangeOperationResultStatus"]] = None, + properties: Optional["_models.ExchangeResponseProperties"] = None, + error: Optional["_models.OperationResultError"] = None, **kwargs ): """ @@ -1084,15 +1105,15 @@ def __init__( :keyword name: It must match the last segment of the id field, and will typically be a GUID / system generated value. :paramtype name: str - :keyword status: Status of the operation. Possible values include: "Succeeded", "Failed", - "Cancelled", "PendingRefunds", "PendingPurchases". + :keyword status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", + "PendingRefunds", and "PendingPurchases". :paramtype status: str or ~azure.mgmt.reservations.models.ExchangeOperationResultStatus :keyword properties: Exchange response properties. :paramtype properties: ~azure.mgmt.reservations.models.ExchangeResponseProperties :keyword error: Required if status == failed or status == canceled. :paramtype error: ~azure.mgmt.reservations.models.OperationResultError """ - super(ExchangeOperationResultResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.name = name self.status = status @@ -1100,7 +1121,7 @@ def __init__( self.error = error -class ExchangePolicyError(msrest.serialization.Model): +class ExchangePolicyError(_serialization.Model): """error details. :ivar code: @@ -1110,29 +1131,23 @@ class ExchangePolicyError(msrest.serialization.Model): """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - *, - code: Optional[str] = None, - message: Optional[str] = None, - **kwargs - ): + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs): """ :keyword code: :paramtype code: str :keyword message: :paramtype message: str """ - super(ExchangePolicyError, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message -class ExchangePolicyErrors(msrest.serialization.Model): +class ExchangePolicyErrors(_serialization.Model): """Exchange policy errors. :ivar policy_errors: Exchange Policy errors. @@ -1140,24 +1155,19 @@ class ExchangePolicyErrors(msrest.serialization.Model): """ _attribute_map = { - 'policy_errors': {'key': 'policyErrors', 'type': '[ExchangePolicyError]'}, + "policy_errors": {"key": "policyErrors", "type": "[ExchangePolicyError]"}, } - def __init__( - self, - *, - policy_errors: Optional[List["ExchangePolicyError"]] = None, - **kwargs - ): + def __init__(self, *, policy_errors: Optional[List["_models.ExchangePolicyError"]] = None, **kwargs): """ :keyword policy_errors: Exchange Policy errors. :paramtype policy_errors: list[~azure.mgmt.reservations.models.ExchangePolicyError] """ - super(ExchangePolicyErrors, self).__init__(**kwargs) + super().__init__(**kwargs) self.policy_errors = policy_errors -class ExchangeRequest(msrest.serialization.Model): +class ExchangeRequest(_serialization.Model): """Exchange request. :ivar properties: Exchange request properties. @@ -1165,24 +1175,19 @@ class ExchangeRequest(msrest.serialization.Model): """ _attribute_map = { - 'properties': {'key': 'properties', 'type': 'ExchangeRequestProperties'}, + "properties": {"key": "properties", "type": "ExchangeRequestProperties"}, } - def __init__( - self, - *, - properties: Optional["ExchangeRequestProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.ExchangeRequestProperties"] = None, **kwargs): """ :keyword properties: Exchange request properties. :paramtype properties: ~azure.mgmt.reservations.models.ExchangeRequestProperties """ - super(ExchangeRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties -class ExchangeRequestProperties(msrest.serialization.Model): +class ExchangeRequestProperties(_serialization.Model): """Exchange request properties. :ivar session_id: SessionId that was returned by CalculateExchange API. @@ -1190,24 +1195,19 @@ class ExchangeRequestProperties(msrest.serialization.Model): """ _attribute_map = { - 'session_id': {'key': 'sessionId', 'type': 'str'}, + "session_id": {"key": "sessionId", "type": "str"}, } - def __init__( - self, - *, - session_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, session_id: Optional[str] = None, **kwargs): """ :keyword session_id: SessionId that was returned by CalculateExchange API. :paramtype session_id: str """ - super(ExchangeRequestProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.session_id = session_id -class ExchangeResponseProperties(msrest.serialization.Model): +class ExchangeResponseProperties(_serialization.Model): """Exchange response properties. :ivar session_id: Exchange session identifier. @@ -1229,25 +1229,25 @@ class ExchangeResponseProperties(msrest.serialization.Model): """ _attribute_map = { - 'session_id': {'key': 'sessionId', 'type': 'str'}, - 'net_payable': {'key': 'netPayable', 'type': 'Price'}, - 'refunds_total': {'key': 'refundsTotal', 'type': 'Price'}, - 'purchases_total': {'key': 'purchasesTotal', 'type': 'Price'}, - 'reservations_to_purchase': {'key': 'reservationsToPurchase', 'type': '[ReservationToPurchaseExchange]'}, - 'reservations_to_exchange': {'key': 'reservationsToExchange', 'type': '[ReservationToReturnForExchange]'}, - 'policy_result': {'key': 'policyResult', 'type': 'ExchangePolicyErrors'}, + "session_id": {"key": "sessionId", "type": "str"}, + "net_payable": {"key": "netPayable", "type": "Price"}, + "refunds_total": {"key": "refundsTotal", "type": "Price"}, + "purchases_total": {"key": "purchasesTotal", "type": "Price"}, + "reservations_to_purchase": {"key": "reservationsToPurchase", "type": "[ReservationToPurchaseExchange]"}, + "reservations_to_exchange": {"key": "reservationsToExchange", "type": "[ReservationToReturnForExchange]"}, + "policy_result": {"key": "policyResult", "type": "ExchangePolicyErrors"}, } def __init__( self, *, session_id: Optional[str] = None, - net_payable: Optional["Price"] = None, - refunds_total: Optional["Price"] = None, - purchases_total: Optional["Price"] = None, - reservations_to_purchase: Optional[List["ReservationToPurchaseExchange"]] = None, - reservations_to_exchange: Optional[List["ReservationToReturnForExchange"]] = None, - policy_result: Optional["ExchangePolicyErrors"] = None, + net_payable: Optional["_models.Price"] = None, + refunds_total: Optional["_models.Price"] = None, + purchases_total: Optional["_models.Price"] = None, + reservations_to_purchase: Optional[List["_models.ReservationToPurchaseExchange"]] = None, + reservations_to_exchange: Optional[List["_models.ReservationToReturnForExchange"]] = None, + policy_result: Optional["_models.ExchangePolicyErrors"] = None, **kwargs ): """ @@ -1268,7 +1268,7 @@ def __init__( :keyword policy_result: Exchange policy errors. :paramtype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors """ - super(ExchangeResponseProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.session_id = session_id self.net_payable = net_payable self.refunds_total = refunds_total @@ -1278,10 +1278,10 @@ def __init__( self.policy_result = policy_result -class ExtendedErrorInfo(msrest.serialization.Model): +class ExtendedErrorInfo(_serialization.Model): """ExtendedErrorInfo. - :ivar code: Possible values include: "NotSpecified", "InternalServerError", "ServerTimeout", + :ivar code: Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", @@ -1299,26 +1299,23 @@ class ExtendedErrorInfo(msrest.serialization.Model): "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", "BillingTransientError", "BillingError", "FulfillmentConfigurationError", "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", - "CalculatePriceFailed", "AppliedScopesSameAsExisting". + "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and + "RefundLimitExceeded". :vartype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode :ivar message: :vartype message: str """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } def __init__( - self, - *, - code: Optional[Union[str, "ErrorResponseCode"]] = None, - message: Optional[str] = None, - **kwargs + self, *, code: Optional[Union[str, "_models.ErrorResponseCode"]] = None, message: Optional[str] = None, **kwargs ): """ - :keyword code: Possible values include: "NotSpecified", "InternalServerError", "ServerTimeout", + :keyword code: Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", @@ -1336,51 +1333,52 @@ def __init__( "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", "BillingTransientError", "BillingError", "FulfillmentConfigurationError", "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", - "CalculatePriceFailed", "AppliedScopesSameAsExisting". + "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and + "RefundLimitExceeded". :paramtype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode :keyword message: :paramtype message: str """ - super(ExtendedErrorInfo, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message -class ExtendedStatusInfo(msrest.serialization.Model): +class ExtendedStatusInfo(_serialization.Model): """ExtendedStatusInfo. - :ivar status_code: Possible values include: "None", "Pending", "Processing", "Active", - "PurchaseError", "PaymentInstrumentError", "Split", "Merged", "Expired", "Succeeded". + :ivar status_code: Known values are: "None", "Pending", "Processing", "Active", + "PurchaseError", "PaymentInstrumentError", "Split", "Merged", "Expired", and "Succeeded". :vartype status_code: str or ~azure.mgmt.reservations.models.ReservationStatusCode :ivar message: The message giving detailed information about the status code. :vartype message: str """ _attribute_map = { - 'status_code': {'key': 'statusCode', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "status_code": {"key": "statusCode", "type": "str"}, + "message": {"key": "message", "type": "str"}, } def __init__( self, *, - status_code: Optional[Union[str, "ReservationStatusCode"]] = None, + status_code: Optional[Union[str, "_models.ReservationStatusCode"]] = None, message: Optional[str] = None, **kwargs ): """ - :keyword status_code: Possible values include: "None", "Pending", "Processing", "Active", - "PurchaseError", "PaymentInstrumentError", "Split", "Merged", "Expired", "Succeeded". + :keyword status_code: Known values are: "None", "Pending", "Processing", "Active", + "PurchaseError", "PaymentInstrumentError", "Split", "Merged", "Expired", and "Succeeded". :paramtype status_code: str or ~azure.mgmt.reservations.models.ReservationStatusCode :keyword message: The message giving detailed information about the status code. :paramtype message: str """ - super(ExtendedStatusInfo, self).__init__(**kwargs) + super().__init__(**kwargs) self.status_code = status_code self.message = message -class MergeRequest(msrest.serialization.Model): +class MergeRequest(_serialization.Model): """MergeRequest. :ivar sources: Format of the resource id should be @@ -1389,25 +1387,20 @@ class MergeRequest(msrest.serialization.Model): """ _attribute_map = { - 'sources': {'key': 'properties.sources', 'type': '[str]'}, + "sources": {"key": "properties.sources", "type": "[str]"}, } - def __init__( - self, - *, - sources: Optional[List[str]] = None, - **kwargs - ): + def __init__(self, *, sources: Optional[List[str]] = None, **kwargs): """ :keyword sources: Format of the resource id should be /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. :paramtype sources: list[str] """ - super(MergeRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.sources = sources -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """OperationDisplay. :ivar provider: @@ -1421,10 +1414,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__( @@ -1446,14 +1439,14 @@ def __init__( :keyword description: :paramtype description: str """ - super(OperationDisplay, self).__init__(**kwargs) + super().__init__(**kwargs) self.provider = provider self.resource = resource self.operation = operation self.description = description -class OperationList(msrest.serialization.Model): +class OperationList(_serialization.Model): """OperationList. :ivar value: @@ -1463,16 +1456,12 @@ class OperationList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[OperationResponse]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[OperationResponse]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["OperationResponse"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.OperationResponse"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: @@ -1480,12 +1469,12 @@ def __init__( :keyword next_link: Url to get the next page of items. :paramtype next_link: str """ - super(OperationList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class OperationResponse(msrest.serialization.Model): +class OperationResponse(_serialization.Model): """OperationResponse. :ivar name: Name of the operation. @@ -1497,15 +1486,15 @@ class OperationResponse(msrest.serialization.Model): :ivar origin: Origin of the operation. :vartype origin: str :ivar properties: Properties of the operation. - :vartype properties: any + :vartype properties: JSON """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'object'}, + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "object"}, } def __init__( @@ -1513,9 +1502,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[Any] = None, + properties: Optional[JSON] = None, **kwargs ): """ @@ -1528,9 +1517,9 @@ def __init__( :keyword origin: Origin of the operation. :paramtype origin: str :keyword properties: Properties of the operation. - :paramtype properties: any + :paramtype properties: JSON """ - super(OperationResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.display = display @@ -1538,7 +1527,7 @@ def __init__( self.properties = properties -class OperationResultError(msrest.serialization.Model): +class OperationResultError(_serialization.Model): """Required if status == failed or status == canceled. :ivar code: Required if status == failed or status == cancelled. If status == failed, provide @@ -1551,17 +1540,11 @@ class OperationResultError(msrest.serialization.Model): """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - *, - code: Optional[str] = None, - message: Optional[str] = None, - **kwargs - ): + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs): """ :keyword code: Required if status == failed or status == cancelled. If status == failed, provide an invariant error code used for error troubleshooting, aggregation, and analysis. @@ -1571,23 +1554,22 @@ def __init__( the issue. :paramtype message: str """ - super(OperationResultError, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message -class Patch(msrest.serialization.Model): +class Patch(_serialization.Model): """Patch. - :ivar applied_scope_type: Type of the Applied Scope. Possible values include: "Single", - "Shared". + :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single" and "Shared". :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType :ivar applied_scopes: List of the subscriptions that the benefit will be applied. Do not specify if AppliedScopeType is Shared. :vartype applied_scopes: list[str] :ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in - the same VM size group. Only specify for VirtualMachines reserved resource type. Possible - values include: "On", "Off". + the same VM size group. Only specify for VirtualMachines reserved resource type. Known values + are: "On" and "Off". :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility :ivar name: Name of the Reservation. :vartype name: str @@ -1599,35 +1581,35 @@ class Patch(msrest.serialization.Model): """ _attribute_map = { - 'applied_scope_type': {'key': 'properties.appliedScopeType', 'type': 'str'}, - 'applied_scopes': {'key': 'properties.appliedScopes', 'type': '[str]'}, - 'instance_flexibility': {'key': 'properties.instanceFlexibility', 'type': 'str'}, - 'name': {'key': 'properties.name', 'type': 'str'}, - 'renew': {'key': 'properties.renew', 'type': 'bool'}, - 'renew_properties': {'key': 'properties.renewProperties', 'type': 'PatchPropertiesRenewProperties'}, + "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, + "applied_scopes": {"key": "properties.appliedScopes", "type": "[str]"}, + "instance_flexibility": {"key": "properties.instanceFlexibility", "type": "str"}, + "name": {"key": "properties.name", "type": "str"}, + "renew": {"key": "properties.renew", "type": "bool"}, + "renew_properties": {"key": "properties.renewProperties", "type": "PatchPropertiesRenewProperties"}, } def __init__( self, *, - applied_scope_type: Optional[Union[str, "AppliedScopeType"]] = None, + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, applied_scopes: Optional[List[str]] = None, - instance_flexibility: Optional[Union[str, "InstanceFlexibility"]] = None, + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, name: Optional[str] = None, - renew: Optional[bool] = False, - renew_properties: Optional["PatchPropertiesRenewProperties"] = None, + renew: bool = False, + renew_properties: Optional["_models.PatchPropertiesRenewProperties"] = None, **kwargs ): """ - :keyword applied_scope_type: Type of the Applied Scope. Possible values include: "Single", + :keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single" and "Shared". :paramtype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType :keyword applied_scopes: List of the subscriptions that the benefit will be applied. Do not specify if AppliedScopeType is Shared. :paramtype applied_scopes: list[str] :keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs - in the same VM size group. Only specify for VirtualMachines reserved resource type. Possible - values include: "On", "Off". + in the same VM size group. Only specify for VirtualMachines reserved resource type. Known + values are: "On" and "Off". :paramtype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility :keyword name: Name of the Reservation. :paramtype name: str @@ -1637,7 +1619,7 @@ def __init__( :keyword renew_properties: :paramtype renew_properties: ~azure.mgmt.reservations.models.PatchPropertiesRenewProperties """ - super(Patch, self).__init__(**kwargs) + super().__init__(**kwargs) self.applied_scope_type = applied_scope_type self.applied_scopes = applied_scopes self.instance_flexibility = instance_flexibility @@ -1646,7 +1628,7 @@ def __init__( self.renew_properties = renew_properties -class PatchPropertiesRenewProperties(msrest.serialization.Model): +class PatchPropertiesRenewProperties(_serialization.Model): """PatchPropertiesRenewProperties. :ivar purchase_properties: @@ -1654,24 +1636,19 @@ class PatchPropertiesRenewProperties(msrest.serialization.Model): """ _attribute_map = { - 'purchase_properties': {'key': 'purchaseProperties', 'type': 'PurchaseRequest'}, + "purchase_properties": {"key": "purchaseProperties", "type": "PurchaseRequest"}, } - def __init__( - self, - *, - purchase_properties: Optional["PurchaseRequest"] = None, - **kwargs - ): + def __init__(self, *, purchase_properties: Optional["_models.PurchaseRequest"] = None, **kwargs): """ :keyword purchase_properties: :paramtype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest """ - super(PatchPropertiesRenewProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.purchase_properties = purchase_properties -class PaymentDetail(msrest.serialization.Model): +class PaymentDetail(_serialization.Model): """Information about payment related to a reservation order. :ivar due_date: Date when the payment needs to be done. @@ -1686,20 +1663,20 @@ class PaymentDetail(msrest.serialization.Model): :ivar billing_account: Shows the Account that is charged for this payment. :vartype billing_account: str :ivar status: Describes whether the payment is completed, failed, cancelled or scheduled in the - future. Possible values include: "Succeeded", "Failed", "Scheduled", "Cancelled". + future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled". :vartype status: str or ~azure.mgmt.reservations.models.PaymentStatus :ivar extended_status_info: :vartype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo """ _attribute_map = { - 'due_date': {'key': 'dueDate', 'type': 'date'}, - 'payment_date': {'key': 'paymentDate', 'type': 'date'}, - 'pricing_currency_total': {'key': 'pricingCurrencyTotal', 'type': 'Price'}, - 'billing_currency_total': {'key': 'billingCurrencyTotal', 'type': 'Price'}, - 'billing_account': {'key': 'billingAccount', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'extended_status_info': {'key': 'extendedStatusInfo', 'type': 'ExtendedStatusInfo'}, + "due_date": {"key": "dueDate", "type": "date"}, + "payment_date": {"key": "paymentDate", "type": "date"}, + "pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"}, + "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, + "billing_account": {"key": "billingAccount", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "extended_status_info": {"key": "extendedStatusInfo", "type": "ExtendedStatusInfo"}, } def __init__( @@ -1707,11 +1684,11 @@ def __init__( *, due_date: Optional[datetime.date] = None, payment_date: Optional[datetime.date] = None, - pricing_currency_total: Optional["Price"] = None, - billing_currency_total: Optional["Price"] = None, + pricing_currency_total: Optional["_models.Price"] = None, + billing_currency_total: Optional["_models.Price"] = None, billing_account: Optional[str] = None, - status: Optional[Union[str, "PaymentStatus"]] = None, - extended_status_info: Optional["ExtendedStatusInfo"] = None, + status: Optional[Union[str, "_models.PaymentStatus"]] = None, + extended_status_info: Optional["_models.ExtendedStatusInfo"] = None, **kwargs ): """ @@ -1727,12 +1704,12 @@ def __init__( :keyword billing_account: Shows the Account that is charged for this payment. :paramtype billing_account: str :keyword status: Describes whether the payment is completed, failed, cancelled or scheduled in - the future. Possible values include: "Succeeded", "Failed", "Scheduled", "Cancelled". + the future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled". :paramtype status: str or ~azure.mgmt.reservations.models.PaymentStatus :keyword extended_status_info: :paramtype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo """ - super(PaymentDetail, self).__init__(**kwargs) + super().__init__(**kwargs) self.due_date = due_date self.payment_date = payment_date self.pricing_currency_total = pricing_currency_total @@ -1742,7 +1719,7 @@ def __init__( self.extended_status_info = extended_status_info -class Price(msrest.serialization.Model): +class Price(_serialization.Model): """Price. :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase @@ -1753,17 +1730,11 @@ class Price(msrest.serialization.Model): """ _attribute_map = { - 'currency_code': {'key': 'currencyCode', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "amount": {"key": "amount", "type": "float"}, } - def __init__( - self, - *, - currency_code: Optional[str] = None, - amount: Optional[float] = None, - **kwargs - ): + def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs): """ :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase record. @@ -1771,37 +1742,36 @@ def __init__( :keyword amount: :paramtype amount: float """ - super(Price, self).__init__(**kwargs) + super().__init__(**kwargs) self.currency_code = currency_code self.amount = amount -class PurchaseRequest(msrest.serialization.Model): +class PurchaseRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes """PurchaseRequest. :ivar sku: :vartype sku: ~azure.mgmt.reservations.models.SkuName :ivar location: The Azure Region where the reserved resource lives. :vartype location: str - :ivar reserved_resource_type: The type of the resource that is being reserved. Possible values - include: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", - "SqlDataWarehouse", "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", - "ManagedDisk", "BlockBlob", "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", - "PostgreSql", "DedicatedHost", "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", - "NetAppStorage", "AzureFiles", "SqlEdge", "VirtualMachineSoftware". + :ivar reserved_resource_type: The type of the resource that is being reserved. Known values + are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", + "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", + "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", + "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", + "SqlEdge", and "VirtualMachineSoftware". :vartype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType :ivar billing_scope_id: Subscription that will be charged for purchasing Reservation. :vartype billing_scope_id: str - :ivar term: Represent the term of Reservation. Possible values include: "P1Y", "P3Y", "P5Y". + :ivar term: Represent the term of Reservation. Known values are: "P1Y", "P3Y", and "P5Y". :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :ivar billing_plan: Represent the billing plans. Possible values include: "Upfront", "Monthly". + :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan :ivar quantity: Quantity of the SKUs that are part of the Reservation. :vartype quantity: int :ivar display_name: Friendly name of the Reservation. :vartype display_name: str - :ivar applied_scope_type: Type of the Applied Scope. Possible values include: "Single", - "Shared". + :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single" and "Shared". :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType :ivar applied_scopes: List of the subscriptions that the benefit will be applied. Do not specify if AppliedScopeType is Shared. @@ -1816,35 +1786,38 @@ class PurchaseRequest(msrest.serialization.Model): """ _attribute_map = { - 'sku': {'key': 'sku', 'type': 'SkuName'}, - 'location': {'key': 'location', 'type': 'str'}, - 'reserved_resource_type': {'key': 'properties.reservedResourceType', 'type': 'str'}, - 'billing_scope_id': {'key': 'properties.billingScopeId', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'billing_plan': {'key': 'properties.billingPlan', 'type': 'str'}, - 'quantity': {'key': 'properties.quantity', 'type': 'int'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'applied_scope_type': {'key': 'properties.appliedScopeType', 'type': 'str'}, - 'applied_scopes': {'key': 'properties.appliedScopes', 'type': '[str]'}, - 'renew': {'key': 'properties.renew', 'type': 'bool'}, - 'reserved_resource_properties': {'key': 'properties.reservedResourceProperties', 'type': 'PurchaseRequestPropertiesReservedResourceProperties'}, + "sku": {"key": "sku", "type": "SkuName"}, + "location": {"key": "location", "type": "str"}, + "reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"}, + "billing_scope_id": {"key": "properties.billingScopeId", "type": "str"}, + "term": {"key": "properties.term", "type": "str"}, + "billing_plan": {"key": "properties.billingPlan", "type": "str"}, + "quantity": {"key": "properties.quantity", "type": "int"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, + "applied_scopes": {"key": "properties.appliedScopes", "type": "[str]"}, + "renew": {"key": "properties.renew", "type": "bool"}, + "reserved_resource_properties": { + "key": "properties.reservedResourceProperties", + "type": "PurchaseRequestPropertiesReservedResourceProperties", + }, } def __init__( self, *, - sku: Optional["SkuName"] = None, + sku: Optional["_models.SkuName"] = None, location: Optional[str] = None, - reserved_resource_type: Optional[Union[str, "ReservedResourceType"]] = None, + reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None, billing_scope_id: Optional[str] = None, - term: Optional[Union[str, "ReservationTerm"]] = None, - billing_plan: Optional[Union[str, "ReservationBillingPlan"]] = None, + term: Optional[Union[str, "_models.ReservationTerm"]] = None, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, quantity: Optional[int] = None, display_name: Optional[str] = None, - applied_scope_type: Optional[Union[str, "AppliedScopeType"]] = None, + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, applied_scopes: Optional[List[str]] = None, - renew: Optional[bool] = False, - reserved_resource_properties: Optional["PurchaseRequestPropertiesReservedResourceProperties"] = None, + renew: bool = False, + reserved_resource_properties: Optional["_models.PurchaseRequestPropertiesReservedResourceProperties"] = None, **kwargs ): """ @@ -1852,25 +1825,24 @@ def __init__( :paramtype sku: ~azure.mgmt.reservations.models.SkuName :keyword location: The Azure Region where the reserved resource lives. :paramtype location: str - :keyword reserved_resource_type: The type of the resource that is being reserved. Possible - values include: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", - "SqlDataWarehouse", "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", - "ManagedDisk", "BlockBlob", "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", - "PostgreSql", "DedicatedHost", "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", - "NetAppStorage", "AzureFiles", "SqlEdge", "VirtualMachineSoftware". + :keyword reserved_resource_type: The type of the resource that is being reserved. Known values + are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", + "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", + "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", + "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", + "SqlEdge", and "VirtualMachineSoftware". :paramtype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType :keyword billing_scope_id: Subscription that will be charged for purchasing Reservation. :paramtype billing_scope_id: str - :keyword term: Represent the term of Reservation. Possible values include: "P1Y", "P3Y", "P5Y". + :keyword term: Represent the term of Reservation. Known values are: "P1Y", "P3Y", and "P5Y". :paramtype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :keyword billing_plan: Represent the billing plans. Possible values include: "Upfront", - "Monthly". + :keyword billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan :keyword quantity: Quantity of the SKUs that are part of the Reservation. :paramtype quantity: int :keyword display_name: Friendly name of the Reservation. :paramtype display_name: str - :keyword applied_scope_type: Type of the Applied Scope. Possible values include: "Single", + :keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single" and "Shared". :paramtype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType :keyword applied_scopes: List of the subscriptions that the benefit will be applied. Do not @@ -1884,7 +1856,7 @@ def __init__( :paramtype reserved_resource_properties: ~azure.mgmt.reservations.models.PurchaseRequestPropertiesReservedResourceProperties """ - super(PurchaseRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.sku = sku self.location = location self.reserved_resource_type = reserved_resource_type @@ -1899,36 +1871,31 @@ def __init__( self.reserved_resource_properties = reserved_resource_properties -class PurchaseRequestPropertiesReservedResourceProperties(msrest.serialization.Model): +class PurchaseRequestPropertiesReservedResourceProperties(_serialization.Model): """Properties specific to each reserved resource type. Not required if not applicable. :ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in - the same VM size group. Only specify for VirtualMachines reserved resource type. Possible - values include: "On", "Off". + the same VM size group. Only specify for VirtualMachines reserved resource type. Known values + are: "On" and "Off". :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility """ _attribute_map = { - 'instance_flexibility': {'key': 'instanceFlexibility', 'type': 'str'}, + "instance_flexibility": {"key": "instanceFlexibility", "type": "str"}, } - def __init__( - self, - *, - instance_flexibility: Optional[Union[str, "InstanceFlexibility"]] = None, - **kwargs - ): + def __init__(self, *, instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, **kwargs): """ :keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs - in the same VM size group. Only specify for VirtualMachines reserved resource type. Possible - values include: "On", "Off". + in the same VM size group. Only specify for VirtualMachines reserved resource type. Known + values are: "On" and "Off". :paramtype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility """ - super(PurchaseRequestPropertiesReservedResourceProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.instance_flexibility = instance_flexibility -class QuotaLimits(msrest.serialization.Model): +class QuotaLimits(_serialization.Model): """Quota limits. :ivar value: List of quotas (service limits). @@ -1939,14 +1906,14 @@ class QuotaLimits(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[CurrentQuotaLimitBase]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[CurrentQuotaLimitBase]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["CurrentQuotaLimitBase"]] = None, + value: Optional[List["_models.CurrentQuotaLimitBase"]] = None, next_link: Optional[str] = None, **kwargs ): @@ -1957,12 +1924,12 @@ def __init__( pages exist, the value is null. :paramtype next_link: str """ - super(QuotaLimits, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class QuotaLimitsResponse(msrest.serialization.Model): +class QuotaLimitsResponse(_serialization.Model): """Quotas (service limits) in the request response. :ivar value: List of quotas with the quota request status. @@ -1973,16 +1940,12 @@ class QuotaLimitsResponse(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[CurrentQuotaLimit]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[CurrentQuotaLimit]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["CurrentQuotaLimit"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.CurrentQuotaLimit"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: List of quotas with the quota request status. @@ -1991,12 +1954,12 @@ def __init__( exist, the value is null. :paramtype next_link: str """ - super(QuotaLimitsResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class QuotaProperties(msrest.serialization.Model): +class QuotaProperties(_serialization.Model): """Quota properties for the resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2011,30 +1974,30 @@ class QuotaProperties(msrest.serialization.Model): :ivar name: Name of the resource provide by the resource provider. Use this property for quotaRequests resource operations. :vartype name: ~azure.mgmt.reservations.models.ResourceName - :ivar resource_type: The name of the resource type. Possible values include: "standard", - "dedicated", "lowPriority", "shared", "serviceSpecific". + :ivar resource_type: The name of the resource type. Known values are: "standard", "dedicated", + "lowPriority", "shared", and "serviceSpecific". :vartype resource_type: str or ~azure.mgmt.reservations.models.ResourceType :ivar quota_period: The time period over which the quota usage values are summarized. For example, P1D (per one day), PT1M (per one minute), and PT1S (per one second). This parameter is optional because, for some resources such as compute, the time period is irrelevant. :vartype quota_period: str :ivar properties: Additional properties for the specified resource provider. - :vartype properties: any + :vartype properties: JSON """ _validation = { - 'current_value': {'readonly': True}, - 'quota_period': {'readonly': True}, + "current_value": {"readonly": True}, + "quota_period": {"readonly": True}, } _attribute_map = { - 'limit': {'key': 'limit', 'type': 'int'}, - 'current_value': {'key': 'currentValue', 'type': 'int'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'ResourceName'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'quota_period': {'key': 'quotaPeriod', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'object'}, + "limit": {"key": "limit", "type": "int"}, + "current_value": {"key": "currentValue", "type": "int"}, + "unit": {"key": "unit", "type": "str"}, + "name": {"key": "name", "type": "ResourceName"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "quota_period": {"key": "quotaPeriod", "type": "str"}, + "properties": {"key": "properties", "type": "object"}, } def __init__( @@ -2042,9 +2005,9 @@ def __init__( *, limit: Optional[int] = None, unit: Optional[str] = None, - name: Optional["ResourceName"] = None, - resource_type: Optional[Union[str, "ResourceType"]] = None, - properties: Optional[Any] = None, + name: Optional["_models.ResourceName"] = None, + resource_type: Optional[Union[str, "_models.ResourceType"]] = None, + properties: Optional[JSON] = None, **kwargs ): """ @@ -2056,13 +2019,13 @@ def __init__( :keyword name: Name of the resource provide by the resource provider. Use this property for quotaRequests resource operations. :paramtype name: ~azure.mgmt.reservations.models.ResourceName - :keyword resource_type: The name of the resource type. Possible values include: "standard", - "dedicated", "lowPriority", "shared", "serviceSpecific". + :keyword resource_type: The name of the resource type. Known values are: "standard", + "dedicated", "lowPriority", "shared", and "serviceSpecific". :paramtype resource_type: str or ~azure.mgmt.reservations.models.ResourceType :keyword properties: Additional properties for the specified resource provider. - :paramtype properties: any + :paramtype properties: JSON """ - super(QuotaProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.limit = limit self.current_value = None self.unit = unit @@ -2072,7 +2035,7 @@ def __init__( self.properties = properties -class QuotaRequestDetails(msrest.serialization.Model): +class QuotaRequestDetails(_serialization.Model): """Quota request details. Variables are only populated by the server, and will be ignored when sending a request. @@ -2083,8 +2046,8 @@ class QuotaRequestDetails(msrest.serialization.Model): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar provisioning_state: The quota request status. Possible values include: "Accepted", - "Invalid", "Succeeded", "Failed", "InProgress". + :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :ivar message: User friendly status message. :vartype message: str @@ -2096,38 +2059,38 @@ class QuotaRequestDetails(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'message': {'readonly': True}, - 'request_submit_time': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "message": {"readonly": True}, + "request_submit_time": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'message': {'key': 'properties.message', 'type': 'str'}, - 'request_submit_time': {'key': 'properties.requestSubmitTime', 'type': 'iso-8601'}, - 'value': {'key': 'properties.value', 'type': '[SubRequest]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "message": {"key": "properties.message", "type": "str"}, + "request_submit_time": {"key": "properties.requestSubmitTime", "type": "iso-8601"}, + "value": {"key": "properties.value", "type": "[SubRequest]"}, } def __init__( self, *, - provisioning_state: Optional[Union[str, "QuotaRequestState"]] = None, - value: Optional[List["SubRequest"]] = None, + provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = None, + value: Optional[List["_models.SubRequest"]] = None, **kwargs ): """ - :keyword provisioning_state: The quota request status. Possible values include: "Accepted", - "Invalid", "Succeeded", "Failed", "InProgress". + :keyword provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :keyword value: The quotaRequests. :paramtype value: list[~azure.mgmt.reservations.models.SubRequest] """ - super(QuotaRequestDetails, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -2137,7 +2100,7 @@ def __init__( self.value = value -class QuotaRequestDetailsList(msrest.serialization.Model): +class QuotaRequestDetailsList(_serialization.Model): """Quota request details. :ivar value: The quota requests. @@ -2148,16 +2111,12 @@ class QuotaRequestDetailsList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[QuotaRequestDetails]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[QuotaRequestDetails]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["QuotaRequestDetails"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.QuotaRequestDetails"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The quota requests. @@ -2166,12 +2125,12 @@ def __init__( pages, this is null. :paramtype next_link: str """ - super(QuotaRequestDetailsList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class QuotaRequestOneResourceSubmitResponse(msrest.serialization.Model): +class QuotaRequestOneResourceSubmitResponse(_serialization.Model): """Response for the quota submission request. Variables are only populated by the server, and will be ignored when sending a request. @@ -2182,8 +2141,8 @@ class QuotaRequestOneResourceSubmitResponse(msrest.serialization.Model): :vartype name: str :ivar type: Type of resource. "Microsoft.Capacity/ServiceLimits". :vartype type: str - :ivar provisioning_state: The quota request status. Possible values include: "Accepted", - "Invalid", "Succeeded", "Failed", "InProgress". + :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :ivar message: User friendly status message. :vartype message: str @@ -2201,41 +2160,36 @@ class QuotaRequestOneResourceSubmitResponse(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'message': {'readonly': True}, - 'request_submit_time': {'readonly': True}, - 'id_properties_id': {'readonly': True}, - 'name_properties_name': {'readonly': True}, - 'type_properties_type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'message': {'key': 'properties.message', 'type': 'str'}, - 'request_submit_time': {'key': 'properties.requestSubmitTime', 'type': 'iso-8601'}, - 'id_properties_id': {'key': 'properties.properties.id', 'type': 'str'}, - 'name_properties_name': {'key': 'properties.properties.name', 'type': 'str'}, - 'type_properties_type': {'key': 'properties.properties.type', 'type': 'str'}, - 'properties': {'key': 'properties.properties.properties', 'type': 'QuotaProperties'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "message": {"readonly": True}, + "request_submit_time": {"readonly": True}, + "id_properties_id": {"readonly": True}, + "name_properties_name": {"readonly": True}, + "type_properties_type": {"readonly": True}, } - def __init__( - self, - *, - properties: Optional["QuotaProperties"] = None, - **kwargs - ): + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "message": {"key": "properties.message", "type": "str"}, + "request_submit_time": {"key": "properties.requestSubmitTime", "type": "iso-8601"}, + "id_properties_id": {"key": "properties.properties.id", "type": "str"}, + "name_properties_name": {"key": "properties.properties.name", "type": "str"}, + "type_properties_type": {"key": "properties.properties.type", "type": "str"}, + "properties": {"key": "properties.properties.properties", "type": "QuotaProperties"}, + } + + def __init__(self, *, properties: Optional["_models.QuotaProperties"] = None, **kwargs): """ :keyword properties: Quota properties for the resource. :paramtype properties: ~azure.mgmt.reservations.models.QuotaProperties """ - super(QuotaRequestOneResourceSubmitResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -2248,13 +2202,13 @@ def __init__( self.properties = properties -class QuotaRequestProperties(msrest.serialization.Model): +class QuotaRequestProperties(_serialization.Model): """The details of quota request. Variables are only populated by the server, and will be ignored when sending a request. - :ivar provisioning_state: The quota request status. Possible values include: "Accepted", - "Invalid", "Succeeded", "Failed", "InProgress". + :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :ivar message: User friendly status message. :vartype message: str @@ -2266,39 +2220,39 @@ class QuotaRequestProperties(msrest.serialization.Model): """ _validation = { - 'message': {'readonly': True}, - 'request_submit_time': {'readonly': True}, + "message": {"readonly": True}, + "request_submit_time": {"readonly": True}, } _attribute_map = { - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'request_submit_time': {'key': 'requestSubmitTime', 'type': 'iso-8601'}, - 'value': {'key': 'value', 'type': '[SubRequest]'}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "request_submit_time": {"key": "requestSubmitTime", "type": "iso-8601"}, + "value": {"key": "value", "type": "[SubRequest]"}, } def __init__( self, *, - provisioning_state: Optional[Union[str, "QuotaRequestState"]] = None, - value: Optional[List["SubRequest"]] = None, + provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = None, + value: Optional[List["_models.SubRequest"]] = None, **kwargs ): """ - :keyword provisioning_state: The quota request status. Possible values include: "Accepted", - "Invalid", "Succeeded", "Failed", "InProgress". + :keyword provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :keyword value: The quotaRequests. :paramtype value: list[~azure.mgmt.reservations.models.SubRequest] """ - super(QuotaRequestProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.provisioning_state = provisioning_state self.message = None self.request_submit_time = None self.value = value -class QuotaRequestSubmitResponse(msrest.serialization.Model): +class QuotaRequestSubmitResponse(_serialization.Model): """Response for the quota submission request. Variables are only populated by the server, and will be ignored when sending a request. @@ -2314,36 +2268,31 @@ class QuotaRequestSubmitResponse(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'}, - 'properties': {'key': 'properties', 'type': 'QuotaRequestProperties'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "QuotaRequestProperties"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - properties: Optional["QuotaRequestProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.QuotaRequestProperties"] = None, **kwargs): """ :keyword properties: The quota request details. :paramtype properties: ~azure.mgmt.reservations.models.QuotaRequestProperties """ - super(QuotaRequestSubmitResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.properties = properties self.type = None -class QuotaRequestSubmitResponse201(msrest.serialization.Model): +class QuotaRequestSubmitResponse201(_serialization.Model): """Response with request ID that the quota request was accepted. Variables are only populated by the server, and will be ignored when sending a request. @@ -2354,36 +2303,32 @@ class QuotaRequestSubmitResponse201(msrest.serialization.Model): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar provisioning_state: The details of the quota request status. Possible values include: - "Accepted", "Invalid", "Succeeded", "Failed", "InProgress". + :ivar provisioning_state: The details of the quota request status. Known values are: + "Accepted", "Invalid", "Succeeded", "Failed", and "InProgress". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :ivar message: A user friendly message. :vartype message: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'message': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "message": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'message': {'key': 'properties.message', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "message": {"key": "properties.message", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(QuotaRequestSubmitResponse201, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -2391,33 +2336,387 @@ def __init__( self.message = None -class RenewPropertiesResponse(msrest.serialization.Model): - """RenewPropertiesResponse. - - :ivar purchase_properties: - :vartype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest - :ivar pricing_currency_total: Amount that Microsoft uses for record. Used during refund for - calculating refund limit. Tax is not included. This is locked price 30 days before expiry. - :vartype pricing_currency_total: - ~azure.mgmt.reservations.models.RenewPropertiesResponsePricingCurrencyTotal - :ivar billing_currency_total: Currency and amount that customer will be charged in customer's - local currency for renewal purchase. Tax is not included. - :vartype billing_currency_total: - ~azure.mgmt.reservations.models.RenewPropertiesResponseBillingCurrencyTotal - """ +class RefundBillingInformation(_serialization.Model): + """billing information. + + :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". + :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan + :ivar completed_transactions: The number of completed transactions in this reservation's + payment. + :vartype completed_transactions: int + :ivar total_transactions: The number of total transactions in this reservation's payment. + :vartype total_transactions: int + :ivar billing_currency_total_paid_amount: + :vartype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_currency_prorated_amount: + :vartype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_currency_remaining_commitment_amount: + :vartype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price + """ + + _attribute_map = { + "billing_plan": {"key": "billingPlan", "type": "str"}, + "completed_transactions": {"key": "completedTransactions", "type": "int"}, + "total_transactions": {"key": "totalTransactions", "type": "int"}, + "billing_currency_total_paid_amount": {"key": "billingCurrencyTotalPaidAmount", "type": "Price"}, + "billing_currency_prorated_amount": {"key": "billingCurrencyProratedAmount", "type": "Price"}, + "billing_currency_remaining_commitment_amount": { + "key": "billingCurrencyRemainingCommitmentAmount", + "type": "Price", + }, + } + + def __init__( + self, + *, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, + completed_transactions: Optional[int] = None, + total_transactions: Optional[int] = None, + billing_currency_total_paid_amount: Optional["_models.Price"] = None, + billing_currency_prorated_amount: Optional["_models.Price"] = None, + billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None, + **kwargs + ): + """ + :keyword billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". + :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan + :keyword completed_transactions: The number of completed transactions in this reservation's + payment. + :paramtype completed_transactions: int + :keyword total_transactions: The number of total transactions in this reservation's payment. + :paramtype total_transactions: int + :keyword billing_currency_total_paid_amount: + :paramtype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price + :keyword billing_currency_prorated_amount: + :paramtype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price + :keyword billing_currency_remaining_commitment_amount: + :paramtype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price + """ + super().__init__(**kwargs) + self.billing_plan = billing_plan + self.completed_transactions = completed_transactions + self.total_transactions = total_transactions + self.billing_currency_total_paid_amount = billing_currency_total_paid_amount + self.billing_currency_prorated_amount = billing_currency_prorated_amount + self.billing_currency_remaining_commitment_amount = billing_currency_remaining_commitment_amount + + +class RefundPolicyError(_serialization.Model): + """error details. + + :ivar code: Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", + "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", + "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", + "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", + "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", + "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", + "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", + "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", + "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", + "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", + "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", + "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", + "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", + "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", + "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", + "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", + "BillingTransientError", "BillingError", "FulfillmentConfigurationError", + "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", + "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and + "RefundLimitExceeded". + :vartype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode + :ivar message: + :vartype message: str + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__( + self, *, code: Optional[Union[str, "_models.ErrorResponseCode"]] = None, message: Optional[str] = None, **kwargs + ): + """ + :keyword code: Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", + "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", + "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", + "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", + "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", + "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", + "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", + "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", + "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", + "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", + "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", + "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", + "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", + "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", + "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", + "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", + "BillingTransientError", "BillingError", "FulfillmentConfigurationError", + "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", + "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and + "RefundLimitExceeded". + :paramtype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode + :keyword message: + :paramtype message: str + """ + super().__init__(**kwargs) + self.code = code + self.message = message + + +class RefundPolicyResult(_serialization.Model): + """Refund policy result. + + :ivar properties: Refund policy result property. + :vartype properties: ~azure.mgmt.reservations.models.RefundPolicyResultProperty + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "RefundPolicyResultProperty"}, + } + + def __init__(self, *, properties: Optional["_models.RefundPolicyResultProperty"] = None, **kwargs): + """ + :keyword properties: Refund policy result property. + :paramtype properties: ~azure.mgmt.reservations.models.RefundPolicyResultProperty + """ + super().__init__(**kwargs) + self.properties = properties + + +class RefundPolicyResultProperty(_serialization.Model): + """Refund policy result property. + + :ivar consumed_refunds_total: + :vartype consumed_refunds_total: ~azure.mgmt.reservations.models.Price + :ivar max_refund_limit: + :vartype max_refund_limit: ~azure.mgmt.reservations.models.Price + :ivar policy_errors: Refund Policy errors. + :vartype policy_errors: list[~azure.mgmt.reservations.models.RefundPolicyError] + """ + + _attribute_map = { + "consumed_refunds_total": {"key": "consumedRefundsTotal", "type": "Price"}, + "max_refund_limit": {"key": "maxRefundLimit", "type": "Price"}, + "policy_errors": {"key": "policyErrors", "type": "[RefundPolicyError]"}, + } + + def __init__( + self, + *, + consumed_refunds_total: Optional["_models.Price"] = None, + max_refund_limit: Optional["_models.Price"] = None, + policy_errors: Optional[List["_models.RefundPolicyError"]] = None, + **kwargs + ): + """ + :keyword consumed_refunds_total: + :paramtype consumed_refunds_total: ~azure.mgmt.reservations.models.Price + :keyword max_refund_limit: + :paramtype max_refund_limit: ~azure.mgmt.reservations.models.Price + :keyword policy_errors: Refund Policy errors. + :paramtype policy_errors: list[~azure.mgmt.reservations.models.RefundPolicyError] + """ + super().__init__(**kwargs) + self.consumed_refunds_total = consumed_refunds_total + self.max_refund_limit = max_refund_limit + self.policy_errors = policy_errors + + +class RefundRequest(_serialization.Model): + """RefundRequest. + + :ivar properties: + :vartype properties: ~azure.mgmt.reservations.models.RefundRequestProperties + """ + + _attribute_map = { + "properties": {"key": "properties", "type": "RefundRequestProperties"}, + } + + def __init__(self, *, properties: Optional["_models.RefundRequestProperties"] = None, **kwargs): + """ + :keyword properties: + :paramtype properties: ~azure.mgmt.reservations.models.RefundRequestProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class RefundRequestProperties(_serialization.Model): + """RefundRequestProperties. + + :ivar session_id: SessionId that was returned by CalculateRefund API. + :vartype session_id: str + :ivar scope: The scope of the refund, e.g. Reservation. + :vartype scope: str + :ivar reservation_to_return: Reservation to return. + :vartype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn + :ivar return_reason: The reason of returning the reservation. + :vartype return_reason: str + """ + + _attribute_map = { + "session_id": {"key": "sessionId", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + "reservation_to_return": {"key": "reservationToReturn", "type": "ReservationToReturn"}, + "return_reason": {"key": "returnReason", "type": "str"}, + } + + def __init__( + self, + *, + session_id: Optional[str] = None, + scope: Optional[str] = None, + reservation_to_return: Optional["_models.ReservationToReturn"] = None, + return_reason: Optional[str] = None, + **kwargs + ): + """ + :keyword session_id: SessionId that was returned by CalculateRefund API. + :paramtype session_id: str + :keyword scope: The scope of the refund, e.g. Reservation. + :paramtype scope: str + :keyword reservation_to_return: Reservation to return. + :paramtype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn + :keyword return_reason: The reason of returning the reservation. + :paramtype return_reason: str + """ + super().__init__(**kwargs) + self.session_id = session_id + self.scope = scope + self.reservation_to_return = reservation_to_return + self.return_reason = return_reason + + +class RefundResponse(_serialization.Model): + """RefundResponse. + + :ivar id: Fully qualified identifier of the reservation being returned. + :vartype id: str + :ivar properties: + :vartype properties: ~azure.mgmt.reservations.models.RefundResponseProperties + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "properties": {"key": "properties", "type": "RefundResponseProperties"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + properties: Optional["_models.RefundResponseProperties"] = None, + **kwargs + ): + """ + :keyword id: Fully qualified identifier of the reservation being returned. + :paramtype id: str + :keyword properties: + :paramtype properties: ~azure.mgmt.reservations.models.RefundResponseProperties + """ + super().__init__(**kwargs) + self.id = id + self.properties = properties + + +class RefundResponseProperties(_serialization.Model): + """RefundResponseProperties. + + :ivar session_id: Refund session identifier. + :vartype session_id: str + :ivar quantity: Quantity to be returned. + :vartype quantity: int + :ivar billing_refund_amount: + :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price + :ivar pricing_refund_amount: + :vartype pricing_refund_amount: ~azure.mgmt.reservations.models.Price + :ivar policy_result: Refund policy result. + :vartype policy_result: ~azure.mgmt.reservations.models.RefundPolicyResult + :ivar billing_information: billing information. + :vartype billing_information: ~azure.mgmt.reservations.models.RefundBillingInformation + """ _attribute_map = { - 'purchase_properties': {'key': 'purchaseProperties', 'type': 'PurchaseRequest'}, - 'pricing_currency_total': {'key': 'pricingCurrencyTotal', 'type': 'RenewPropertiesResponsePricingCurrencyTotal'}, - 'billing_currency_total': {'key': 'billingCurrencyTotal', 'type': 'RenewPropertiesResponseBillingCurrencyTotal'}, + "session_id": {"key": "sessionId", "type": "str"}, + "quantity": {"key": "quantity", "type": "int"}, + "billing_refund_amount": {"key": "billingRefundAmount", "type": "Price"}, + "pricing_refund_amount": {"key": "pricingRefundAmount", "type": "Price"}, + "policy_result": {"key": "policyResult", "type": "RefundPolicyResult"}, + "billing_information": {"key": "billingInformation", "type": "RefundBillingInformation"}, } def __init__( self, *, - purchase_properties: Optional["PurchaseRequest"] = None, - pricing_currency_total: Optional["RenewPropertiesResponsePricingCurrencyTotal"] = None, - billing_currency_total: Optional["RenewPropertiesResponseBillingCurrencyTotal"] = None, + session_id: Optional[str] = None, + quantity: Optional[int] = None, + billing_refund_amount: Optional["_models.Price"] = None, + pricing_refund_amount: Optional["_models.Price"] = None, + policy_result: Optional["_models.RefundPolicyResult"] = None, + billing_information: Optional["_models.RefundBillingInformation"] = None, + **kwargs + ): + """ + :keyword session_id: Refund session identifier. + :paramtype session_id: str + :keyword quantity: Quantity to be returned. + :paramtype quantity: int + :keyword billing_refund_amount: + :paramtype billing_refund_amount: ~azure.mgmt.reservations.models.Price + :keyword pricing_refund_amount: + :paramtype pricing_refund_amount: ~azure.mgmt.reservations.models.Price + :keyword policy_result: Refund policy result. + :paramtype policy_result: ~azure.mgmt.reservations.models.RefundPolicyResult + :keyword billing_information: billing information. + :paramtype billing_information: ~azure.mgmt.reservations.models.RefundBillingInformation + """ + super().__init__(**kwargs) + self.session_id = session_id + self.quantity = quantity + self.billing_refund_amount = billing_refund_amount + self.pricing_refund_amount = pricing_refund_amount + self.policy_result = policy_result + self.billing_information = billing_information + + +class RenewPropertiesResponse(_serialization.Model): + """RenewPropertiesResponse. + + :ivar purchase_properties: + :vartype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest + :ivar pricing_currency_total: Amount that Microsoft uses for record. Used during refund for + calculating refund limit. Tax is not included. This is locked price 30 days before expiry. + :vartype pricing_currency_total: + ~azure.mgmt.reservations.models.RenewPropertiesResponsePricingCurrencyTotal + :ivar billing_currency_total: Currency and amount that customer will be charged in customer's + local currency for renewal purchase. Tax is not included. + :vartype billing_currency_total: + ~azure.mgmt.reservations.models.RenewPropertiesResponseBillingCurrencyTotal + """ + + _attribute_map = { + "purchase_properties": {"key": "purchaseProperties", "type": "PurchaseRequest"}, + "pricing_currency_total": { + "key": "pricingCurrencyTotal", + "type": "RenewPropertiesResponsePricingCurrencyTotal", + }, + "billing_currency_total": { + "key": "billingCurrencyTotal", + "type": "RenewPropertiesResponseBillingCurrencyTotal", + }, + } + + def __init__( + self, + *, + purchase_properties: Optional["_models.PurchaseRequest"] = None, + pricing_currency_total: Optional["_models.RenewPropertiesResponsePricingCurrencyTotal"] = None, + billing_currency_total: Optional["_models.RenewPropertiesResponseBillingCurrencyTotal"] = None, **kwargs ): """ @@ -2432,13 +2731,13 @@ def __init__( :paramtype billing_currency_total: ~azure.mgmt.reservations.models.RenewPropertiesResponseBillingCurrencyTotal """ - super(RenewPropertiesResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.purchase_properties = purchase_properties self.pricing_currency_total = pricing_currency_total self.billing_currency_total = billing_currency_total -class RenewPropertiesResponseBillingCurrencyTotal(msrest.serialization.Model): +class RenewPropertiesResponseBillingCurrencyTotal(_serialization.Model): """Currency and amount that customer will be charged in customer's local currency for renewal purchase. Tax is not included. :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase @@ -2449,17 +2748,11 @@ class RenewPropertiesResponseBillingCurrencyTotal(msrest.serialization.Model): """ _attribute_map = { - 'currency_code': {'key': 'currencyCode', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "amount": {"key": "amount", "type": "float"}, } - def __init__( - self, - *, - currency_code: Optional[str] = None, - amount: Optional[float] = None, - **kwargs - ): + def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs): """ :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase record. @@ -2467,12 +2760,12 @@ def __init__( :keyword amount: :paramtype amount: float """ - super(RenewPropertiesResponseBillingCurrencyTotal, self).__init__(**kwargs) + super().__init__(**kwargs) self.currency_code = currency_code self.amount = amount -class RenewPropertiesResponsePricingCurrencyTotal(msrest.serialization.Model): +class RenewPropertiesResponsePricingCurrencyTotal(_serialization.Model): """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is not included. This is locked price 30 days before expiry. :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase @@ -2483,17 +2776,11 @@ class RenewPropertiesResponsePricingCurrencyTotal(msrest.serialization.Model): """ _attribute_map = { - 'currency_code': {'key': 'currencyCode', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "amount": {"key": "amount", "type": "float"}, } - def __init__( - self, - *, - currency_code: Optional[str] = None, - amount: Optional[float] = None, - **kwargs - ): + def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs): """ :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase record. @@ -2501,12 +2788,12 @@ def __init__( :keyword amount: :paramtype amount: float """ - super(RenewPropertiesResponsePricingCurrencyTotal, self).__init__(**kwargs) + super().__init__(**kwargs) self.currency_code = currency_code self.amount = amount -class ReservationList(msrest.serialization.Model): +class ReservationList(_serialization.Model): """ReservationList. :ivar value: @@ -2516,16 +2803,12 @@ class ReservationList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ReservationResponse]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ReservationResponse]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["ReservationResponse"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.ReservationResponse"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: @@ -2533,12 +2816,12 @@ def __init__( :keyword next_link: Url to get the next page of reservations. :paramtype next_link: str """ - super(ReservationList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ReservationMergeProperties(msrest.serialization.Model): +class ReservationMergeProperties(_serialization.Model): """ReservationMergeProperties. :ivar merge_destination: Reservation Resource Id Created due to the merge. Format of the @@ -2552,17 +2835,11 @@ class ReservationMergeProperties(msrest.serialization.Model): """ _attribute_map = { - 'merge_destination': {'key': 'mergeDestination', 'type': 'str'}, - 'merge_sources': {'key': 'mergeSources', 'type': '[str]'}, + "merge_destination": {"key": "mergeDestination", "type": "str"}, + "merge_sources": {"key": "mergeSources", "type": "[str]"}, } - def __init__( - self, - *, - merge_destination: Optional[str] = None, - merge_sources: Optional[List[str]] = None, - **kwargs - ): + def __init__(self, *, merge_destination: Optional[str] = None, merge_sources: Optional[List[str]] = None, **kwargs): """ :keyword merge_destination: Reservation Resource Id Created due to the merge. Format of the resource Id is @@ -2573,12 +2850,12 @@ def __init__( /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. :paramtype merge_sources: list[str] """ - super(ReservationMergeProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.merge_destination = merge_destination self.merge_sources = merge_sources -class ReservationOrderBillingPlanInformation(msrest.serialization.Model): +class ReservationOrderBillingPlanInformation(_serialization.Model): """Information describing the type of billing plan for this reservation. :ivar pricing_currency_total: Amount of money to be paid for the Order. Tax is not included. @@ -2593,19 +2870,19 @@ class ReservationOrderBillingPlanInformation(msrest.serialization.Model): """ _attribute_map = { - 'pricing_currency_total': {'key': 'pricingCurrencyTotal', 'type': 'Price'}, - 'start_date': {'key': 'startDate', 'type': 'date'}, - 'next_payment_due_date': {'key': 'nextPaymentDueDate', 'type': 'date'}, - 'transactions': {'key': 'transactions', 'type': '[PaymentDetail]'}, + "pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"}, + "start_date": {"key": "startDate", "type": "date"}, + "next_payment_due_date": {"key": "nextPaymentDueDate", "type": "date"}, + "transactions": {"key": "transactions", "type": "[PaymentDetail]"}, } def __init__( self, *, - pricing_currency_total: Optional["Price"] = None, + pricing_currency_total: Optional["_models.Price"] = None, start_date: Optional[datetime.date] = None, next_payment_due_date: Optional[datetime.date] = None, - transactions: Optional[List["PaymentDetail"]] = None, + transactions: Optional[List["_models.PaymentDetail"]] = None, **kwargs ): """ @@ -2619,14 +2896,14 @@ def __init__( :keyword transactions: :paramtype transactions: list[~azure.mgmt.reservations.models.PaymentDetail] """ - super(ReservationOrderBillingPlanInformation, self).__init__(**kwargs) + super().__init__(**kwargs) self.pricing_currency_total = pricing_currency_total self.start_date = start_date self.next_payment_due_date = next_payment_due_date self.transactions = transactions -class ReservationOrderList(msrest.serialization.Model): +class ReservationOrderList(_serialization.Model): """ReservationOrderList. :ivar value: @@ -2636,14 +2913,14 @@ class ReservationOrderList(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ReservationOrderResponse]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ReservationOrderResponse]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( self, *, - value: Optional[List["ReservationOrderResponse"]] = None, + value: Optional[List["_models.ReservationOrderResponse"]] = None, next_link: Optional[str] = None, **kwargs ): @@ -2653,12 +2930,12 @@ def __init__( :keyword next_link: Url to get the next page of reservationOrders. :paramtype next_link: str """ - super(ReservationOrderList, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ReservationOrderResponse(msrest.serialization.Model): +class ReservationOrderResponse(_serialization.Model): # pylint: disable=too-many-instance-attributes """ReservationOrderResponse. Variables are only populated by the server, and will be ignored when sending a request. @@ -2686,14 +2963,14 @@ class ReservationOrderResponse(msrest.serialization.Model): :vartype benefit_start_time: ~datetime.datetime :ivar original_quantity: Total Quantity of the SKUs purchased in the Reservation. :vartype original_quantity: int - :ivar term: Represent the term of Reservation. Possible values include: "P1Y", "P3Y", "P5Y". + :ivar term: Represent the term of Reservation. Known values are: "P1Y", "P3Y", and "P5Y". :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :ivar provisioning_state: Current state of the reservation. Possible values include: - "Creating", "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", - "ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", - "Split", "Merged". + :ivar provisioning_state: Current state of the reservation. Known values are: "Creating", + "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", + "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and + "Merged". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState - :ivar billing_plan: Represent the billing plans. Possible values include: "Upfront", "Monthly". + :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan :ivar plan_information: Information describing the type of billing plan for this reservation. :vartype plan_information: @@ -2703,29 +2980,29 @@ class ReservationOrderResponse(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - } - - _attribute_map = { - 'etag': {'key': 'etag', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'request_date_time': {'key': 'properties.requestDateTime', 'type': 'iso-8601'}, - 'created_date_time': {'key': 'properties.createdDateTime', 'type': 'iso-8601'}, - 'expiry_date': {'key': 'properties.expiryDate', 'type': 'date'}, - 'benefit_start_time': {'key': 'properties.benefitStartTime', 'type': 'iso-8601'}, - 'original_quantity': {'key': 'properties.originalQuantity', 'type': 'int'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'billing_plan': {'key': 'properties.billingPlan', 'type': 'str'}, - 'plan_information': {'key': 'properties.planInformation', 'type': 'ReservationOrderBillingPlanInformation'}, - 'reservations': {'key': 'properties.reservations', 'type': '[ReservationResponse]'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "etag": {"key": "etag", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "request_date_time": {"key": "properties.requestDateTime", "type": "iso-8601"}, + "created_date_time": {"key": "properties.createdDateTime", "type": "iso-8601"}, + "expiry_date": {"key": "properties.expiryDate", "type": "date"}, + "benefit_start_time": {"key": "properties.benefitStartTime", "type": "iso-8601"}, + "original_quantity": {"key": "properties.originalQuantity", "type": "int"}, + "term": {"key": "properties.term", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "billing_plan": {"key": "properties.billingPlan", "type": "str"}, + "plan_information": {"key": "properties.planInformation", "type": "ReservationOrderBillingPlanInformation"}, + "reservations": {"key": "properties.reservations", "type": "[ReservationResponse]"}, } def __init__( @@ -2738,11 +3015,11 @@ def __init__( expiry_date: Optional[datetime.date] = None, benefit_start_time: Optional[datetime.datetime] = None, original_quantity: Optional[int] = None, - term: Optional[Union[str, "ReservationTerm"]] = None, - provisioning_state: Optional[Union[str, "ProvisioningState"]] = None, - billing_plan: Optional[Union[str, "ReservationBillingPlan"]] = None, - plan_information: Optional["ReservationOrderBillingPlanInformation"] = None, - reservations: Optional[List["ReservationResponse"]] = None, + term: Optional[Union[str, "_models.ReservationTerm"]] = None, + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, + plan_information: Optional["_models.ReservationOrderBillingPlanInformation"] = None, + reservations: Optional[List["_models.ReservationResponse"]] = None, **kwargs ): """ @@ -2761,15 +3038,14 @@ def __init__( :paramtype benefit_start_time: ~datetime.datetime :keyword original_quantity: Total Quantity of the SKUs purchased in the Reservation. :paramtype original_quantity: int - :keyword term: Represent the term of Reservation. Possible values include: "P1Y", "P3Y", "P5Y". + :keyword term: Represent the term of Reservation. Known values are: "P1Y", "P3Y", and "P5Y". :paramtype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :keyword provisioning_state: Current state of the reservation. Possible values include: - "Creating", "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", - "ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", - "Split", "Merged". + :keyword provisioning_state: Current state of the reservation. Known values are: "Creating", + "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", + "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and + "Merged". :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState - :keyword billing_plan: Represent the billing plans. Possible values include: "Upfront", - "Monthly". + :keyword billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan :keyword plan_information: Information describing the type of billing plan for this reservation. @@ -2778,7 +3054,7 @@ def __init__( :keyword reservations: :paramtype reservations: list[~azure.mgmt.reservations.models.ReservationResponse] """ - super(ReservationOrderResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.etag = etag self.id = None self.name = None @@ -2797,7 +3073,7 @@ def __init__( self.reservations = reservations -class ReservationResponse(msrest.serialization.Model): +class ReservationResponse(_serialization.Model): """The definition of the reservation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2816,30 +3092,29 @@ class ReservationResponse(msrest.serialization.Model): :vartype properties: ~azure.mgmt.reservations.models.ReservationsProperties :ivar type: Type of resource. "Microsoft.Capacity/reservationOrders/reservations". :vartype type: str - :ivar kind: Resource Provider type to be reserved. The only acceptable values to pass in are - None and "Microsoft.Compute". The default value is None. + :ivar kind: Resource Provider type to be reserved. Default value is "Microsoft.Compute". :vartype kind: str :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.reservations.models.SystemData """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, } _attribute_map = { - 'location': {'key': 'location', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'SkuName'}, - 'properties': {'key': 'properties', 'type': 'ReservationsProperties'}, - 'type': {'key': 'type', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, + "location": {"key": "location", "type": "str"}, + "etag": {"key": "etag", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "sku": {"key": "sku", "type": "SkuName"}, + "properties": {"key": "properties", "type": "ReservationsProperties"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, } def __init__( @@ -2847,8 +3122,8 @@ def __init__( *, location: Optional[str] = None, etag: Optional[int] = None, - sku: Optional["SkuName"] = None, - properties: Optional["ReservationsProperties"] = None, + sku: Optional["_models.SkuName"] = None, + properties: Optional["_models.ReservationsProperties"] = None, kind: Optional[str] = None, **kwargs ): @@ -2861,11 +3136,10 @@ def __init__( :paramtype sku: ~azure.mgmt.reservations.models.SkuName :keyword properties: The properties associated to this reservation. :paramtype properties: ~azure.mgmt.reservations.models.ReservationsProperties - :keyword kind: Resource Provider type to be reserved. The only acceptable values to pass in are - None and "Microsoft.Compute". The default value is None. + :keyword kind: Resource Provider type to be reserved. Default value is "Microsoft.Compute". :paramtype kind: str """ - super(ReservationResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.location = location self.etag = etag self.id = None @@ -2877,7 +3151,7 @@ def __init__( self.system_data = None -class ReservationsListResult(msrest.serialization.Model): +class ReservationsListResult(_serialization.Model): """The list of reservations and summary of roll out count of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. @@ -2891,33 +3165,28 @@ class ReservationsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ReservationResponse]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'summary': {'key': 'summary', 'type': 'ReservationSummary'}, + "value": {"key": "value", "type": "[ReservationResponse]"}, + "next_link": {"key": "nextLink", "type": "str"}, + "summary": {"key": "summary", "type": "ReservationSummary"}, } - def __init__( - self, - *, - summary: Optional["ReservationSummary"] = None, - **kwargs - ): + def __init__(self, *, summary: Optional["_models.ReservationSummary"] = None, **kwargs): """ :keyword summary: The roll out count summary of the reservations. :paramtype summary: ~azure.mgmt.reservations.models.ReservationSummary """ - super(ReservationsListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = None self.next_link = None self.summary = summary -class ReservationSplitProperties(msrest.serialization.Model): +class ReservationSplitProperties(_serialization.Model): """ReservationSplitProperties. :ivar split_destinations: List of destination Resource Id that are created due to split. Format @@ -2931,17 +3200,11 @@ class ReservationSplitProperties(msrest.serialization.Model): """ _attribute_map = { - 'split_destinations': {'key': 'splitDestinations', 'type': '[str]'}, - 'split_source': {'key': 'splitSource', 'type': 'str'}, + "split_destinations": {"key": "splitDestinations", "type": "[str]"}, + "split_source": {"key": "splitSource", "type": "str"}, } - def __init__( - self, - *, - split_destinations: Optional[List[str]] = None, - split_source: Optional[str] = None, - **kwargs - ): + def __init__(self, *, split_destinations: Optional[List[str]] = None, split_source: Optional[str] = None, **kwargs): """ :keyword split_destinations: List of destination Resource Id that are created due to split. Format of the resource Id is @@ -2952,32 +3215,32 @@ def __init__( /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. :paramtype split_source: str """ - super(ReservationSplitProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.split_destinations = split_destinations self.split_source = split_source -class ReservationsProperties(msrest.serialization.Model): +class ReservationsProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """The properties of the reservations. Variables are only populated by the server, and will be ignored when sending a request. - :ivar reserved_resource_type: The type of the resource that is being reserved. Possible values - include: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", - "SqlDataWarehouse", "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", - "ManagedDisk", "BlockBlob", "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", - "PostgreSql", "DedicatedHost", "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", - "NetAppStorage", "AzureFiles", "SqlEdge", "VirtualMachineSoftware". + :ivar reserved_resource_type: The type of the resource that is being reserved. Known values + are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", + "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", + "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", + "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", + "SqlEdge", and "VirtualMachineSoftware". :vartype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType :ivar instance_flexibility: Allows reservation discount to be applied across skus within the - same Autofit group. Not all skus support instance size flexibility. Possible values include: - "On", "Off". + same Autofit group. Not all skus support instance size flexibility. Known values are: "On" and + "Off". :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility :ivar display_name: Friendly name for user to easily identify the reservation. :vartype display_name: str :ivar applied_scopes: The list of applied scopes. :vartype applied_scopes: list[str] - :ivar applied_scope_type: The applied scope type. Possible values include: "Single", "Shared". + :ivar applied_scope_type: The applied scope type. Known values are: "Single" and "Shared". :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType :ivar archived: Indicates if the reservation is archived. :vartype archived: bool @@ -2985,10 +3248,10 @@ class ReservationsProperties(msrest.serialization.Model): :vartype capabilities: str :ivar quantity: Quantity of the SKUs that are part of the Reservation. :vartype quantity: int - :ivar provisioning_state: Current state of the reservation. Possible values include: - "Creating", "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", - "ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", - "Split", "Merged". + :ivar provisioning_state: Current state of the reservation. Known values are: "Creating", + "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", + "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and + "Merged". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState :ivar effective_date_time: DateTime of the Reservation starting when this version is effective from. @@ -3003,8 +3266,8 @@ class ReservationsProperties(msrest.serialization.Model): :vartype sku_description: str :ivar extended_status_info: The message giving detailed information about the status code. :vartype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo - :ivar billing_plan: The billing plan options available for this SKU. Possible values include: - "Upfront", "Monthly". + :ivar billing_plan: The billing plan options available for this SKU. Known values are: + "Upfront" and "Monthly". :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan :ivar display_provisioning_state: The provisioning state of the reservation for display, e.g. Succeeded. @@ -3032,7 +3295,7 @@ class ReservationsProperties(msrest.serialization.Model): :vartype renew_destination: str :ivar renew_properties: :vartype renew_properties: ~azure.mgmt.reservations.models.RenewPropertiesResponse - :ivar term: Represent the term of Reservation. Possible values include: "P1Y", "P3Y", "P5Y". + :ivar term: Represent the term of Reservation. Known values are: "P1Y", "P3Y", and "P5Y". :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm :ivar user_friendly_applied_scope_type: The applied scope type of the reservation for display, e.g. Shared. @@ -3044,94 +3307,93 @@ class ReservationsProperties(msrest.serialization.Model): """ _validation = { - 'last_updated_date_time': {'readonly': True}, - 'display_provisioning_state': {'readonly': True}, - 'provisioning_sub_state': {'readonly': True}, - 'user_friendly_applied_scope_type': {'readonly': True}, - 'user_friendly_renew_state': {'readonly': True}, - 'utilization': {'readonly': True}, - } - - _attribute_map = { - 'reserved_resource_type': {'key': 'reservedResourceType', 'type': 'str'}, - 'instance_flexibility': {'key': 'instanceFlexibility', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'applied_scopes': {'key': 'appliedScopes', 'type': '[str]'}, - 'applied_scope_type': {'key': 'appliedScopeType', 'type': 'str'}, - 'archived': {'key': 'archived', 'type': 'bool'}, - 'capabilities': {'key': 'capabilities', 'type': 'str'}, - 'quantity': {'key': 'quantity', 'type': 'int'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'effective_date_time': {'key': 'effectiveDateTime', 'type': 'iso-8601'}, - 'benefit_start_time': {'key': 'benefitStartTime', 'type': 'iso-8601'}, - 'last_updated_date_time': {'key': 'lastUpdatedDateTime', 'type': 'iso-8601'}, - 'expiry_date': {'key': 'expiryDate', 'type': 'date'}, - 'sku_description': {'key': 'skuDescription', 'type': 'str'}, - 'extended_status_info': {'key': 'extendedStatusInfo', 'type': 'ExtendedStatusInfo'}, - 'billing_plan': {'key': 'billingPlan', 'type': 'str'}, - 'display_provisioning_state': {'key': 'displayProvisioningState', 'type': 'str'}, - 'provisioning_sub_state': {'key': 'provisioningSubState', 'type': 'str'}, - 'purchase_date': {'key': 'purchaseDate', 'type': 'date'}, - 'split_properties': {'key': 'splitProperties', 'type': 'ReservationSplitProperties'}, - 'merge_properties': {'key': 'mergeProperties', 'type': 'ReservationMergeProperties'}, - 'billing_scope_id': {'key': 'billingScopeId', 'type': 'str'}, - 'renew': {'key': 'renew', 'type': 'bool'}, - 'renew_source': {'key': 'renewSource', 'type': 'str'}, - 'renew_destination': {'key': 'renewDestination', 'type': 'str'}, - 'renew_properties': {'key': 'renewProperties', 'type': 'RenewPropertiesResponse'}, - 'term': {'key': 'term', 'type': 'str'}, - 'user_friendly_applied_scope_type': {'key': 'userFriendlyAppliedScopeType', 'type': 'str'}, - 'user_friendly_renew_state': {'key': 'userFriendlyRenewState', 'type': 'str'}, - 'utilization': {'key': 'utilization', 'type': 'ReservationsPropertiesUtilization'}, + "last_updated_date_time": {"readonly": True}, + "display_provisioning_state": {"readonly": True}, + "provisioning_sub_state": {"readonly": True}, + "user_friendly_applied_scope_type": {"readonly": True}, + "user_friendly_renew_state": {"readonly": True}, + "utilization": {"readonly": True}, } - def __init__( + _attribute_map = { + "reserved_resource_type": {"key": "reservedResourceType", "type": "str"}, + "instance_flexibility": {"key": "instanceFlexibility", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + "applied_scopes": {"key": "appliedScopes", "type": "[str]"}, + "applied_scope_type": {"key": "appliedScopeType", "type": "str"}, + "archived": {"key": "archived", "type": "bool"}, + "capabilities": {"key": "capabilities", "type": "str"}, + "quantity": {"key": "quantity", "type": "int"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "effective_date_time": {"key": "effectiveDateTime", "type": "iso-8601"}, + "benefit_start_time": {"key": "benefitStartTime", "type": "iso-8601"}, + "last_updated_date_time": {"key": "lastUpdatedDateTime", "type": "iso-8601"}, + "expiry_date": {"key": "expiryDate", "type": "date"}, + "sku_description": {"key": "skuDescription", "type": "str"}, + "extended_status_info": {"key": "extendedStatusInfo", "type": "ExtendedStatusInfo"}, + "billing_plan": {"key": "billingPlan", "type": "str"}, + "display_provisioning_state": {"key": "displayProvisioningState", "type": "str"}, + "provisioning_sub_state": {"key": "provisioningSubState", "type": "str"}, + "purchase_date": {"key": "purchaseDate", "type": "date"}, + "split_properties": {"key": "splitProperties", "type": "ReservationSplitProperties"}, + "merge_properties": {"key": "mergeProperties", "type": "ReservationMergeProperties"}, + "billing_scope_id": {"key": "billingScopeId", "type": "str"}, + "renew": {"key": "renew", "type": "bool"}, + "renew_source": {"key": "renewSource", "type": "str"}, + "renew_destination": {"key": "renewDestination", "type": "str"}, + "renew_properties": {"key": "renewProperties", "type": "RenewPropertiesResponse"}, + "term": {"key": "term", "type": "str"}, + "user_friendly_applied_scope_type": {"key": "userFriendlyAppliedScopeType", "type": "str"}, + "user_friendly_renew_state": {"key": "userFriendlyRenewState", "type": "str"}, + "utilization": {"key": "utilization", "type": "ReservationsPropertiesUtilization"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, - reserved_resource_type: Optional[Union[str, "ReservedResourceType"]] = None, - instance_flexibility: Optional[Union[str, "InstanceFlexibility"]] = None, + reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None, + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, display_name: Optional[str] = None, applied_scopes: Optional[List[str]] = None, - applied_scope_type: Optional[Union[str, "AppliedScopeType"]] = None, + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, archived: Optional[bool] = None, capabilities: Optional[str] = None, quantity: Optional[int] = None, - provisioning_state: Optional[Union[str, "ProvisioningState"]] = None, + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, effective_date_time: Optional[datetime.datetime] = None, benefit_start_time: Optional[datetime.datetime] = None, expiry_date: Optional[datetime.date] = None, sku_description: Optional[str] = None, - extended_status_info: Optional["ExtendedStatusInfo"] = None, - billing_plan: Optional[Union[str, "ReservationBillingPlan"]] = None, + extended_status_info: Optional["_models.ExtendedStatusInfo"] = None, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, purchase_date: Optional[datetime.date] = None, - split_properties: Optional["ReservationSplitProperties"] = None, - merge_properties: Optional["ReservationMergeProperties"] = None, + split_properties: Optional["_models.ReservationSplitProperties"] = None, + merge_properties: Optional["_models.ReservationMergeProperties"] = None, billing_scope_id: Optional[str] = None, - renew: Optional[bool] = False, + renew: bool = False, renew_source: Optional[str] = None, renew_destination: Optional[str] = None, - renew_properties: Optional["RenewPropertiesResponse"] = None, - term: Optional[Union[str, "ReservationTerm"]] = None, + renew_properties: Optional["_models.RenewPropertiesResponse"] = None, + term: Optional[Union[str, "_models.ReservationTerm"]] = None, **kwargs ): """ - :keyword reserved_resource_type: The type of the resource that is being reserved. Possible - values include: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", - "SqlDataWarehouse", "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", - "ManagedDisk", "BlockBlob", "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", - "PostgreSql", "DedicatedHost", "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", - "NetAppStorage", "AzureFiles", "SqlEdge", "VirtualMachineSoftware". + :keyword reserved_resource_type: The type of the resource that is being reserved. Known values + are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", + "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", + "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", + "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", + "SqlEdge", and "VirtualMachineSoftware". :paramtype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType :keyword instance_flexibility: Allows reservation discount to be applied across skus within the - same Autofit group. Not all skus support instance size flexibility. Possible values include: - "On", "Off". + same Autofit group. Not all skus support instance size flexibility. Known values are: "On" and + "Off". :paramtype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility :keyword display_name: Friendly name for user to easily identify the reservation. :paramtype display_name: str :keyword applied_scopes: The list of applied scopes. :paramtype applied_scopes: list[str] - :keyword applied_scope_type: The applied scope type. Possible values include: "Single", - "Shared". + :keyword applied_scope_type: The applied scope type. Known values are: "Single" and "Shared". :paramtype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType :keyword archived: Indicates if the reservation is archived. :paramtype archived: bool @@ -3139,10 +3401,10 @@ def __init__( :paramtype capabilities: str :keyword quantity: Quantity of the SKUs that are part of the Reservation. :paramtype quantity: int - :keyword provisioning_state: Current state of the reservation. Possible values include: - "Creating", "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", - "ConfirmedBilling", "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", - "Split", "Merged". + :keyword provisioning_state: Current state of the reservation. Known values are: "Creating", + "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", + "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and + "Merged". :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState :keyword effective_date_time: DateTime of the Reservation starting when this version is effective from. @@ -3155,8 +3417,8 @@ def __init__( :paramtype sku_description: str :keyword extended_status_info: The message giving detailed information about the status code. :paramtype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo - :keyword billing_plan: The billing plan options available for this SKU. Possible values - include: "Upfront", "Monthly". + :keyword billing_plan: The billing plan options available for this SKU. Known values are: + "Upfront" and "Monthly". :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan :keyword purchase_date: This is the date when the Reservation was purchased. :paramtype purchase_date: ~datetime.date @@ -3179,10 +3441,10 @@ def __init__( :paramtype renew_destination: str :keyword renew_properties: :paramtype renew_properties: ~azure.mgmt.reservations.models.RenewPropertiesResponse - :keyword term: Represent the term of Reservation. Possible values include: "P1Y", "P3Y", "P5Y". + :keyword term: Represent the term of Reservation. Known values are: "P1Y", "P3Y", and "P5Y". :paramtype term: str or ~azure.mgmt.reservations.models.ReservationTerm """ - super(ReservationsProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.reserved_resource_type = reserved_resource_type self.instance_flexibility = instance_flexibility self.display_name = display_name @@ -3215,7 +3477,7 @@ def __init__( self.utilization = None -class ReservationsPropertiesUtilization(msrest.serialization.Model): +class ReservationsPropertiesUtilization(_serialization.Model): """Reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. @@ -3227,30 +3489,25 @@ class ReservationsPropertiesUtilization(msrest.serialization.Model): """ _validation = { - 'trend': {'readonly': True}, + "trend": {"readonly": True}, } _attribute_map = { - 'trend': {'key': 'trend', 'type': 'str'}, - 'aggregates': {'key': 'aggregates', 'type': '[ReservationUtilizationAggregates]'}, + "trend": {"key": "trend", "type": "str"}, + "aggregates": {"key": "aggregates", "type": "[ReservationUtilizationAggregates]"}, } - def __init__( - self, - *, - aggregates: Optional[List["ReservationUtilizationAggregates"]] = None, - **kwargs - ): + def __init__(self, *, aggregates: Optional[List["_models.ReservationUtilizationAggregates"]] = None, **kwargs): """ :keyword aggregates: The array of aggregates of a reservation's utilization. :paramtype aggregates: list[~azure.mgmt.reservations.models.ReservationUtilizationAggregates] """ - super(ReservationsPropertiesUtilization, self).__init__(**kwargs) + super().__init__(**kwargs) self.trend = None self.aggregates = aggregates -class ReservationSummary(msrest.serialization.Model): +class ReservationSummary(_serialization.Model): """The roll up count summary of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. @@ -3272,32 +3529,28 @@ class ReservationSummary(msrest.serialization.Model): """ _validation = { - 'succeeded_count': {'readonly': True}, - 'failed_count': {'readonly': True}, - 'expiring_count': {'readonly': True}, - 'expired_count': {'readonly': True}, - 'pending_count': {'readonly': True}, - 'cancelled_count': {'readonly': True}, - 'processing_count': {'readonly': True}, + "succeeded_count": {"readonly": True}, + "failed_count": {"readonly": True}, + "expiring_count": {"readonly": True}, + "expired_count": {"readonly": True}, + "pending_count": {"readonly": True}, + "cancelled_count": {"readonly": True}, + "processing_count": {"readonly": True}, } _attribute_map = { - 'succeeded_count': {'key': 'succeededCount', 'type': 'float'}, - 'failed_count': {'key': 'failedCount', 'type': 'float'}, - 'expiring_count': {'key': 'expiringCount', 'type': 'float'}, - 'expired_count': {'key': 'expiredCount', 'type': 'float'}, - 'pending_count': {'key': 'pendingCount', 'type': 'float'}, - 'cancelled_count': {'key': 'cancelledCount', 'type': 'float'}, - 'processing_count': {'key': 'processingCount', 'type': 'float'}, + "succeeded_count": {"key": "succeededCount", "type": "float"}, + "failed_count": {"key": "failedCount", "type": "float"}, + "expiring_count": {"key": "expiringCount", "type": "float"}, + "expired_count": {"key": "expiredCount", "type": "float"}, + "pending_count": {"key": "pendingCount", "type": "float"}, + "cancelled_count": {"key": "cancelledCount", "type": "float"}, + "processing_count": {"key": "processingCount", "type": "float"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationSummary, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.succeeded_count = None self.failed_count = None self.expiring_count = None @@ -3307,7 +3560,7 @@ def __init__( self.processing_count = None -class ReservationToExchange(msrest.serialization.Model): +class ReservationToExchange(_serialization.Model): """Reservation refund details. :ivar reservation_id: Fully qualified id of the Reservation being returned. @@ -3321,10 +3574,10 @@ class ReservationToExchange(msrest.serialization.Model): """ _attribute_map = { - 'reservation_id': {'key': 'reservationId', 'type': 'str'}, - 'quantity': {'key': 'quantity', 'type': 'int'}, - 'billing_refund_amount': {'key': 'billingRefundAmount', 'type': 'Price'}, - 'billing_information': {'key': 'billingInformation', 'type': 'BillingInformation'}, + "reservation_id": {"key": "reservationId", "type": "str"}, + "quantity": {"key": "quantity", "type": "int"}, + "billing_refund_amount": {"key": "billingRefundAmount", "type": "Price"}, + "billing_information": {"key": "billingInformation", "type": "BillingInformation"}, } def __init__( @@ -3332,8 +3585,8 @@ def __init__( *, reservation_id: Optional[str] = None, quantity: Optional[int] = None, - billing_refund_amount: Optional["Price"] = None, - billing_information: Optional["BillingInformation"] = None, + billing_refund_amount: Optional["_models.Price"] = None, + billing_information: Optional["_models.BillingInformation"] = None, **kwargs ): """ @@ -3346,14 +3599,14 @@ def __init__( :keyword billing_information: billing information. :paramtype billing_information: ~azure.mgmt.reservations.models.BillingInformation """ - super(ReservationToExchange, self).__init__(**kwargs) + super().__init__(**kwargs) self.reservation_id = reservation_id self.quantity = quantity self.billing_refund_amount = billing_refund_amount self.billing_information = billing_information -class ReservationToPurchaseCalculateExchange(msrest.serialization.Model): +class ReservationToPurchaseCalculateExchange(_serialization.Model): """Reservation purchase details. :ivar properties: @@ -3363,15 +3616,15 @@ class ReservationToPurchaseCalculateExchange(msrest.serialization.Model): """ _attribute_map = { - 'properties': {'key': 'properties', 'type': 'PurchaseRequest'}, - 'billing_currency_total': {'key': 'billingCurrencyTotal', 'type': 'Price'}, + "properties": {"key": "properties", "type": "PurchaseRequest"}, + "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, } def __init__( self, *, - properties: Optional["PurchaseRequest"] = None, - billing_currency_total: Optional["Price"] = None, + properties: Optional["_models.PurchaseRequest"] = None, + billing_currency_total: Optional["_models.Price"] = None, **kwargs ): """ @@ -3380,12 +3633,12 @@ def __init__( :keyword billing_currency_total: :paramtype billing_currency_total: ~azure.mgmt.reservations.models.Price """ - super(ReservationToPurchaseCalculateExchange, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties self.billing_currency_total = billing_currency_total -class ReservationToPurchaseExchange(msrest.serialization.Model): +class ReservationToPurchaseExchange(_serialization.Model): """Reservation purchase details. :ivar reservation_order_id: Fully qualified id of the ReservationOrder being purchased. @@ -3397,17 +3650,17 @@ class ReservationToPurchaseExchange(msrest.serialization.Model): :vartype properties: ~azure.mgmt.reservations.models.PurchaseRequest :ivar billing_currency_total: :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price - :ivar status: Status of the individual operation. Possible values include: "Succeeded", - "Failed", "Cancelled", "Pending". + :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", + "Cancelled", and "Pending". :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus """ _attribute_map = { - 'reservation_order_id': {'key': 'reservationOrderId', 'type': 'str'}, - 'reservation_id': {'key': 'reservationId', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'PurchaseRequest'}, - 'billing_currency_total': {'key': 'billingCurrencyTotal', 'type': 'Price'}, - 'status': {'key': 'status', 'type': 'str'}, + "reservation_order_id": {"key": "reservationOrderId", "type": "str"}, + "reservation_id": {"key": "reservationId", "type": "str"}, + "properties": {"key": "properties", "type": "PurchaseRequest"}, + "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, + "status": {"key": "status", "type": "str"}, } def __init__( @@ -3415,9 +3668,9 @@ def __init__( *, reservation_order_id: Optional[str] = None, reservation_id: Optional[str] = None, - properties: Optional["PurchaseRequest"] = None, - billing_currency_total: Optional["Price"] = None, - status: Optional[Union[str, "OperationStatus"]] = None, + properties: Optional["_models.PurchaseRequest"] = None, + billing_currency_total: Optional["_models.Price"] = None, + status: Optional[Union[str, "_models.OperationStatus"]] = None, **kwargs ): """ @@ -3430,11 +3683,11 @@ def __init__( :paramtype properties: ~azure.mgmt.reservations.models.PurchaseRequest :keyword billing_currency_total: :paramtype billing_currency_total: ~azure.mgmt.reservations.models.Price - :keyword status: Status of the individual operation. Possible values include: "Succeeded", - "Failed", "Cancelled", "Pending". + :keyword status: Status of the individual operation. Known values are: "Succeeded", "Failed", + "Cancelled", and "Pending". :paramtype status: str or ~azure.mgmt.reservations.models.OperationStatus """ - super(ReservationToPurchaseExchange, self).__init__(**kwargs) + super().__init__(**kwargs) self.reservation_order_id = reservation_order_id self.reservation_id = reservation_id self.properties = properties @@ -3442,7 +3695,7 @@ def __init__( self.status = status -class ReservationToReturn(msrest.serialization.Model): +class ReservationToReturn(_serialization.Model): """Reservation to return. :ivar reservation_id: Fully qualified identifier of the Reservation being returned. @@ -3452,29 +3705,23 @@ class ReservationToReturn(msrest.serialization.Model): """ _attribute_map = { - 'reservation_id': {'key': 'reservationId', 'type': 'str'}, - 'quantity': {'key': 'quantity', 'type': 'int'}, + "reservation_id": {"key": "reservationId", "type": "str"}, + "quantity": {"key": "quantity", "type": "int"}, } - def __init__( - self, - *, - reservation_id: Optional[str] = None, - quantity: Optional[int] = None, - **kwargs - ): + def __init__(self, *, reservation_id: Optional[str] = None, quantity: Optional[int] = None, **kwargs): """ :keyword reservation_id: Fully qualified identifier of the Reservation being returned. :paramtype reservation_id: str :keyword quantity: Quantity to be returned. Must be greater than zero. :paramtype quantity: int """ - super(ReservationToReturn, self).__init__(**kwargs) + super().__init__(**kwargs) self.reservation_id = reservation_id self.quantity = quantity -class ReservationToReturnForExchange(msrest.serialization.Model): +class ReservationToReturnForExchange(_serialization.Model): """Reservation refund details. :ivar reservation_id: Fully qualified id of the Reservation being returned. @@ -3485,17 +3732,17 @@ class ReservationToReturnForExchange(msrest.serialization.Model): :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price :ivar billing_information: billing information. :vartype billing_information: ~azure.mgmt.reservations.models.BillingInformation - :ivar status: Status of the individual operation. Possible values include: "Succeeded", - "Failed", "Cancelled", "Pending". + :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", + "Cancelled", and "Pending". :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus """ _attribute_map = { - 'reservation_id': {'key': 'reservationId', 'type': 'str'}, - 'quantity': {'key': 'quantity', 'type': 'int'}, - 'billing_refund_amount': {'key': 'billingRefundAmount', 'type': 'Price'}, - 'billing_information': {'key': 'billingInformation', 'type': 'BillingInformation'}, - 'status': {'key': 'status', 'type': 'str'}, + "reservation_id": {"key": "reservationId", "type": "str"}, + "quantity": {"key": "quantity", "type": "int"}, + "billing_refund_amount": {"key": "billingRefundAmount", "type": "Price"}, + "billing_information": {"key": "billingInformation", "type": "BillingInformation"}, + "status": {"key": "status", "type": "str"}, } def __init__( @@ -3503,9 +3750,9 @@ def __init__( *, reservation_id: Optional[str] = None, quantity: Optional[int] = None, - billing_refund_amount: Optional["Price"] = None, - billing_information: Optional["BillingInformation"] = None, - status: Optional[Union[str, "OperationStatus"]] = None, + billing_refund_amount: Optional["_models.Price"] = None, + billing_information: Optional["_models.BillingInformation"] = None, + status: Optional[Union[str, "_models.OperationStatus"]] = None, **kwargs ): """ @@ -3517,11 +3764,11 @@ def __init__( :paramtype billing_refund_amount: ~azure.mgmt.reservations.models.Price :keyword billing_information: billing information. :paramtype billing_information: ~azure.mgmt.reservations.models.BillingInformation - :keyword status: Status of the individual operation. Possible values include: "Succeeded", - "Failed", "Cancelled", "Pending". + :keyword status: Status of the individual operation. Known values are: "Succeeded", "Failed", + "Cancelled", and "Pending". :paramtype status: str or ~azure.mgmt.reservations.models.OperationStatus """ - super(ReservationToReturnForExchange, self).__init__(**kwargs) + super().__init__(**kwargs) self.reservation_id = reservation_id self.quantity = quantity self.billing_refund_amount = billing_refund_amount @@ -3529,7 +3776,7 @@ def __init__( self.status = status -class ReservationUtilizationAggregates(msrest.serialization.Model): +class ReservationUtilizationAggregates(_serialization.Model): """The aggregate values of reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. @@ -3545,33 +3792,29 @@ class ReservationUtilizationAggregates(msrest.serialization.Model): """ _validation = { - 'grain': {'readonly': True}, - 'grain_unit': {'readonly': True}, - 'value': {'readonly': True}, - 'value_unit': {'readonly': True}, + "grain": {"readonly": True}, + "grain_unit": {"readonly": True}, + "value": {"readonly": True}, + "value_unit": {"readonly": True}, } _attribute_map = { - 'grain': {'key': 'grain', 'type': 'float'}, - 'grain_unit': {'key': 'grainUnit', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, - 'value_unit': {'key': 'valueUnit', 'type': 'str'}, + "grain": {"key": "grain", "type": "float"}, + "grain_unit": {"key": "grainUnit", "type": "str"}, + "value": {"key": "value", "type": "float"}, + "value_unit": {"key": "valueUnit", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationUtilizationAggregates, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.grain = None self.grain_unit = None self.value = None self.value_unit = None -class ResourceName(msrest.serialization.Model): +class ResourceName(_serialization.Model): """Resource name provided by the resource provider. Use this property for quotaRequest parameter. Variables are only populated by the server, and will be ignored when sending a request. @@ -3583,30 +3826,25 @@ class ResourceName(msrest.serialization.Model): """ _validation = { - 'localized_value': {'readonly': True}, + "localized_value": {"readonly": True}, } _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, - **kwargs - ): + def __init__(self, *, value: Optional[str] = None, **kwargs): """ :keyword value: Resource name. :paramtype value: str """ - super(ResourceName, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.localized_value = None -class ScopeProperties(msrest.serialization.Model): +class ScopeProperties(_serialization.Model): """ScopeProperties. :ivar scope: @@ -3616,29 +3854,23 @@ class ScopeProperties(msrest.serialization.Model): """ _attribute_map = { - 'scope': {'key': 'scope', 'type': 'str'}, - 'valid': {'key': 'valid', 'type': 'bool'}, + "scope": {"key": "scope", "type": "str"}, + "valid": {"key": "valid", "type": "bool"}, } - def __init__( - self, - *, - scope: Optional[str] = None, - valid: Optional[bool] = None, - **kwargs - ): + def __init__(self, *, scope: Optional[str] = None, valid: Optional[bool] = None, **kwargs): """ :keyword scope: :paramtype scope: str :keyword valid: :paramtype valid: bool """ - super(ScopeProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.scope = scope self.valid = valid -class ServiceError(msrest.serialization.Model): +class ServiceError(_serialization.Model): """The API error details. Variables are only populated by the server, and will be ignored when sending a request. @@ -3652,35 +3884,29 @@ class ServiceError(msrest.serialization.Model): """ _validation = { - 'details': {'readonly': True}, + "details": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ServiceErrorDetail]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "[ServiceErrorDetail]"}, } - def __init__( - self, - *, - code: Optional[str] = None, - message: Optional[str] = None, - **kwargs - ): + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs): """ :keyword code: The error code. :paramtype code: str :keyword message: The error message text. :paramtype message: str """ - super(ServiceError, self).__init__(**kwargs) + super().__init__(**kwargs) self.code = code self.message = message self.details = None -class ServiceErrorDetail(msrest.serialization.Model): +class ServiceErrorDetail(_serialization.Model): """The error details. Variables are only populated by the server, and will be ignored when sending a request. @@ -3692,27 +3918,23 @@ class ServiceErrorDetail(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ServiceErrorDetail, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None -class SkuCapability(msrest.serialization.Model): +class SkuCapability(_serialization.Model): """SkuCapability. :ivar name: An invariant to describe the feature. @@ -3722,29 +3944,23 @@ class SkuCapability(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs): """ :keyword name: An invariant to describe the feature. :paramtype name: str :keyword value: An invariant if the feature is measured by quantity. :paramtype value: str """ - super(SkuCapability, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value -class SkuName(msrest.serialization.Model): +class SkuName(_serialization.Model): """SkuName. :ivar name: @@ -3752,24 +3968,19 @@ class SkuName(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, **kwargs): """ :keyword name: :paramtype name: str """ - super(SkuName, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class SkuProperty(msrest.serialization.Model): +class SkuProperty(_serialization.Model): """SkuProperty. :ivar name: An invariant to describe the feature. @@ -3779,29 +3990,23 @@ class SkuProperty(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - value: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs): """ :keyword name: An invariant to describe the feature. :paramtype name: str :keyword value: An invariant if the feature is measured by quantity. :paramtype value: str """ - super(SkuProperty, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value -class SkuRestriction(msrest.serialization.Model): +class SkuRestriction(_serialization.Model): """SkuRestriction. :ivar type: The type of restrictions. @@ -3814,9 +4019,9 @@ class SkuRestriction(msrest.serialization.Model): """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - 'reason_code': {'key': 'reasonCode', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + "reason_code": {"key": "reasonCode", "type": "str"}, } def __init__( @@ -3836,13 +4041,13 @@ def __init__( :keyword reason_code: The reason for restriction. :paramtype reason_code: str """ - super(SkuRestriction, self).__init__(**kwargs) + super().__init__(**kwargs) self.type = type self.values = values self.reason_code = reason_code -class SplitRequest(msrest.serialization.Model): +class SplitRequest(_serialization.Model): """SplitRequest. :ivar quantities: List of the quantities in the new reservations to create. @@ -3854,17 +4059,11 @@ class SplitRequest(msrest.serialization.Model): """ _attribute_map = { - 'quantities': {'key': 'properties.quantities', 'type': '[int]'}, - 'reservation_id': {'key': 'properties.reservationId', 'type': 'str'}, + "quantities": {"key": "properties.quantities", "type": "[int]"}, + "reservation_id": {"key": "properties.reservationId", "type": "str"}, } - def __init__( - self, - *, - quantities: Optional[List[int]] = None, - reservation_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, quantities: Optional[List[int]] = None, reservation_id: Optional[str] = None, **kwargs): """ :keyword quantities: List of the quantities in the new reservations to create. :paramtype quantities: list[int] @@ -3873,12 +4072,12 @@ def __init__( /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. :paramtype reservation_id: str """ - super(SplitRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.quantities = quantities self.reservation_id = reservation_id -class SubRequest(msrest.serialization.Model): +class SubRequest(_serialization.Model): """The sub-request submitted with the quota request. Variables are only populated by the server, and will be ignored when sending a request. @@ -3892,8 +4091,8 @@ class SubRequest(msrest.serialization.Model): :ivar unit: The limit units, such as **count** and **bytes**. Use the unit field provided in the response of the GET quota operation. :vartype unit: str - :ivar provisioning_state: The quota request status. Possible values include: "Accepted", - "Invalid", "Succeeded", "Failed", "InProgress". + :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState :ivar message: User-friendly status message. :vartype message: str @@ -3902,28 +4101,28 @@ class SubRequest(msrest.serialization.Model): """ _validation = { - 'limit': {'readonly': True}, - 'resource_type': {'readonly': True}, - 'message': {'readonly': True}, - 'sub_request_id': {'readonly': True}, + "limit": {"readonly": True}, + "resource_type": {"readonly": True}, + "message": {"readonly": True}, + "sub_request_id": {"readonly": True}, } _attribute_map = { - 'limit': {'key': 'limit', 'type': 'int'}, - 'name': {'key': 'name', 'type': 'ResourceName'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'sub_request_id': {'key': 'subRequestId', 'type': 'str'}, + "limit": {"key": "limit", "type": "int"}, + "name": {"key": "name", "type": "ResourceName"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "sub_request_id": {"key": "subRequestId", "type": "str"}, } def __init__( self, *, - name: Optional["ResourceName"] = None, + name: Optional["_models.ResourceName"] = None, unit: Optional[str] = None, - provisioning_state: Optional[Union[str, "QuotaRequestState"]] = None, + provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = None, **kwargs ): """ @@ -3932,11 +4131,11 @@ def __init__( :keyword unit: The limit units, such as **count** and **bytes**. Use the unit field provided in the response of the GET quota operation. :paramtype unit: str - :keyword provisioning_state: The quota request status. Possible values include: "Accepted", - "Invalid", "Succeeded", "Failed", "InProgress". + :keyword provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState """ - super(SubRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.limit = None self.name = name self.resource_type = None @@ -3946,7 +4145,7 @@ def __init__( self.sub_request_id = None -class SubscriptionScopeProperties(msrest.serialization.Model): +class SubscriptionScopeProperties(_serialization.Model): """SubscriptionScopeProperties. :ivar scopes: @@ -3954,79 +4153,74 @@ class SubscriptionScopeProperties(msrest.serialization.Model): """ _attribute_map = { - 'scopes': {'key': 'scopes', 'type': '[ScopeProperties]'}, + "scopes": {"key": "scopes", "type": "[ScopeProperties]"}, } - def __init__( - self, - *, - scopes: Optional[List["ScopeProperties"]] = None, - **kwargs - ): + def __init__(self, *, scopes: Optional[List["_models.ScopeProperties"]] = None, **kwargs): """ :keyword scopes: :paramtype scopes: list[~azure.mgmt.reservations.models.ScopeProperties] """ - super(SubscriptionScopeProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.scopes = scopes -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.reservations.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.reservations.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.reservations.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.reservations.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 diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py index 5cf631a610fd..7ae269dcb4f4 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py @@ -10,18 +10,28 @@ from ._azure_reservation_api_operations import AzureReservationAPIOperationsMixin from ._reservation_order_operations import ReservationOrderOperations from ._operation_operations import OperationOperations +from ._calculate_refund_operations import CalculateRefundOperations +from ._return_operations_operations import ReturnOperations from ._calculate_exchange_operations import CalculateExchangeOperations from ._exchange_operations import ExchangeOperations from ._quota_operations import QuotaOperations from ._quota_request_status_operations import QuotaRequestStatusOperations +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__ = [ - 'ReservationOperations', - 'AzureReservationAPIOperationsMixin', - 'ReservationOrderOperations', - 'OperationOperations', - 'CalculateExchangeOperations', - 'ExchangeOperations', - 'QuotaOperations', - 'QuotaRequestStatusOperations', + "ReservationOperations", + "AzureReservationAPIOperationsMixin", + "ReservationOrderOperations", + "OperationOperations", + "CalculateRefundOperations", + "ReturnOperations", + "CalculateExchangeOperations", + "ExchangeOperations", + "QuotaOperations", + "QuotaRequestStatusOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py index f5e89d96616a..d1984c2b8477 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py @@ -8,23 +8,32 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, List, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request, _format_url_section + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_catalog_request( subscription_id: str, *, @@ -35,77 +44,66 @@ def build_get_catalog_request( plan_id: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: 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-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs") 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) # 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") if reserved_resource_type is not None: - _query_parameters['reservedResourceType'] = _SERIALIZER.query("reserved_resource_type", reserved_resource_type, 'str') + _params["reservedResourceType"] = _SERIALIZER.query("reserved_resource_type", reserved_resource_type, "str") if location is not None: - _query_parameters['location'] = _SERIALIZER.query("location", location, 'str') + _params["location"] = _SERIALIZER.query("location", location, "str") if publisher_id is not None: - _query_parameters['publisherId'] = _SERIALIZER.query("publisher_id", publisher_id, 'str') + _params["publisherId"] = _SERIALIZER.query("publisher_id", publisher_id, "str") if offer_id is not None: - _query_parameters['offerId'] = _SERIALIZER.query("offer_id", offer_id, 'str') + _params["offerId"] = _SERIALIZER.query("offer_id", offer_id, "str") if plan_id is not None: - _query_parameters['planId'] = _SERIALIZER.query("plan_id", plan_id, 'str') + _params["planId"] = _SERIALIZER.query("plan_id", plan_id, "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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_applied_reservation_list_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - accept = "application/json" +def build_get_applied_reservation_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations") + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations" + ) 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) # 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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class AzureReservationAPIOperationsMixin(object): + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + +class AzureReservationAPIOperationsMixin(MixinABC): @distributed_trace def get_catalog( self, @@ -116,14 +114,14 @@ def get_catalog( offer_id: Optional[str] = None, plan_id: Optional[str] = None, **kwargs: Any - ) -> List["_models.Catalog"]: + ) -> List[_models.Catalog]: """Get the regions and skus that are available for RI purchase for the specified Azure subscription. Get the regions and skus that are available for RI purchase for the specified Azure subscription. - :param subscription_id: Id of the subscription. + :param subscription_id: Id of the subscription. Required. :type subscription_id: str :param reserved_resource_type: The type of the resource for which the skus should be provided. Default value is None. @@ -137,41 +135,44 @@ def get_catalog( :type offer_id: str :param plan_id: Plan id used to get the third party products. Default value is None. :type plan_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: list of Catalog, or the result of cls(response) + :return: list of Catalog or the result of cls(response) :rtype: list[~azure.mgmt.reservations.models.Catalog] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[List["_models.Catalog"]] 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', "2022-03-01") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[List[_models.Catalog]] - request = build_get_catalog_request( subscription_id=subscription_id, - api_version=api_version, reserved_resource_type=reserved_resource_type, location=location, publisher_id=publisher_id, offer_id=offer_id, plan_id=plan_id, - template_url=self.get_catalog.metadata['url'], + api_version=api_version, + template_url=self.get_catalog.metadata["url"], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -179,59 +180,57 @@ def get_catalog( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('[Catalog]', pipeline_response) + deserialized = self._deserialize("[Catalog]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_catalog.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs"} # type: ignore - + get_catalog.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs"} # type: ignore @distributed_trace - def get_applied_reservation_list( - self, - subscription_id: str, - **kwargs: Any - ) -> "_models.AppliedReservations": + def get_applied_reservation_list(self, subscription_id: str, **kwargs: Any) -> _models.AppliedReservations: """Get list of applicable ``Reservation``\ s. Get applicable ``Reservation``\ s that are applied to this subscription or a resource group under this subscription. - :param subscription_id: Id of the subscription. + :param subscription_id: Id of the subscription. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AppliedReservations, or the result of cls(response) + :return: AppliedReservations or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.AppliedReservations - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AppliedReservations"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AppliedReservations] - request = build_get_applied_reservation_list_request( subscription_id=subscription_id, api_version=api_version, - template_url=self.get_applied_reservation_list.metadata['url'], + template_url=self.get_applied_reservation_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 - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -239,12 +238,11 @@ def get_applied_reservation_list( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AppliedReservations', pipeline_response) + deserialized = self._deserialize("AppliedReservations", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_applied_reservation_list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations"} # type: ignore - + get_applied_reservation_list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py index 81a66d4fd9b5..0633ff15c3c3 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py @@ -6,153 +6,215 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._vendor import _convert_request -T = TypeVar('T') -JSONType = Any +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_post_request_initial( - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_post_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-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/calculateExchange") # 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 - ) - -class CalculateExchangeOperations(object): - """CalculateExchangeOperations 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.reservations.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["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class CalculateExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.AzureReservationAPI`'s + :attr:`calculate_exchange` 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") def _post_initial( - self, - body: "_models.CalculateExchangeRequest", - **kwargs: Any - ) -> Optional["_models.CalculateExchangeOperationResultResponse"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.CalculateExchangeOperationResultResponse"]] + self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any + ) -> Optional[_models.CalculateExchangeOperationResultResponse]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CalculateExchangeOperationResultResponse]] - _json = self._serialize.body(body, 'CalculateExchangeRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CalculateExchangeRequest") - request = build_post_request_initial( + request = build_post_request( api_version=api_version, content_type=content_type, json=_json, - template_url=self._post_initial.metadata['url'], + content=_content, + template_url=self._post_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('CalculateExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("CalculateExchangeOperationResultResponse", pipeline_response) if response.status_code == 202: - response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) - + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _post_initial.metadata = {'url': "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore + _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore + + @overload + def begin_post( + self, body: _models.CalculateExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: Request containing purchases and refunds that need to be executed. Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 CalculateExchangeOperationResultResponse + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: Request containing purchases and refunds that need to be executed. Required. + :type body: 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 CalculateExchangeOperationResultResponse + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_post( - self, - body: "_models.CalculateExchangeRequest", - **kwargs: Any - ) -> LROPoller["_models.CalculateExchangeOperationResultResponse"]: + self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any + ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: """Calculates the refund amounts and price of the new purchases. Calculates price for exchanging ``Reservations`` if there are no policy errors. - :param body: Request containing purchases and refunds that need to be executed. - :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param body: Request containing purchases and refunds that need to be executed. Is either a + model type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -165,45 +227,50 @@ def begin_post( or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.CalculateExchangeOperationResultResponse"] - 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", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CalculateExchangeOperationResultResponse] + 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._post_initial( + raw_result = self._post_initial( # type: ignore body=body, 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('CalculateExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("CalculateExchangeOperationResultResponse", 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, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_post.metadata = {'url': "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore + begin_post.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py new file mode 100644 index 000000000000..6585e56e2503 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py @@ -0,0 +1,207 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_post_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/calculateRefund" + ) + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class CalculateRefundOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.AzureReservationAPI`'s + :attr:`calculate_refund` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def post( + self, + reservation_order_id: str, + body: _models.CalculateRefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CalculateRefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def post( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: 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: CalculateRefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def post( + self, reservation_order_id: str, body: Union[_models.CalculateRefundRequest, IO], **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Is either a model type + or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: CalculateRefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CalculateRefundResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "CalculateRefundRequest") + + request = build_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.post.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CalculateRefundResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/calculateRefund"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py index 1e8e42e1673f..fbb74173e8f2 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py @@ -6,153 +6,215 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._vendor import _convert_request -T = TypeVar('T') -JSONType = Any +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_post_request_initial( - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_post_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-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/exchange") # 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 - ) - -class ExchangeOperations(object): - """ExchangeOperations 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.reservations.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["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.AzureReservationAPI`'s + :attr:`exchange` 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") def _post_initial( - self, - body: "_models.ExchangeRequest", - **kwargs: Any - ) -> Optional["_models.ExchangeOperationResultResponse"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExchangeOperationResultResponse"]] + self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any + ) -> Optional[_models.ExchangeOperationResultResponse]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ExchangeOperationResultResponse]] - _json = self._serialize.body(body, 'ExchangeRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ExchangeRequest") - request = build_post_request_initial( + request = build_post_request( api_version=api_version, content_type=content_type, json=_json, - template_url=self._post_initial.metadata['url'], + content=_content, + template_url=self._post_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('ExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("ExchangeOperationResultResponse", pipeline_response) if response.status_code == 202: - response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) - + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _post_initial.metadata = {'url': "/providers/Microsoft.Capacity/exchange"} # type: ignore + _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} # type: ignore + + @overload + def begin_post( + self, body: _models.ExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: Request containing the refunds and purchases that need to be executed. Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 ExchangeOperationResultResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: Request containing the refunds and purchases that need to be executed. Required. + :type body: 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 ExchangeOperationResultResponse or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_post( - self, - body: "_models.ExchangeRequest", - **kwargs: Any - ) -> LROPoller["_models.ExchangeOperationResultResponse"]: + self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any + ) -> LROPoller[_models.ExchangeOperationResultResponse]: """Exchange Reservation(s). Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - :param body: Request containing the refunds and purchases that need to be executed. - :type body: ~azure.mgmt.reservations.models.ExchangeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param body: Request containing the refunds and purchases that need to be executed. Is either a + model type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -165,45 +227,50 @@ def begin_post( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExchangeOperationResultResponse"] - 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", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExchangeOperationResultResponse] + 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._post_initial( + raw_result = self._post_initial( # type: ignore body=body, 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('ExchangeOperationResultResponse', pipeline_response) + deserialized = self._deserialize("ExchangeOperationResultResponse", 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, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_post.metadata = {'url': "/providers/Microsoft.Capacity/exchange"} # type: ignore + begin_post.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py index f64915950b4d..fea7c9d1854a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py @@ -8,113 +8,112 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._vendor import _convert_request -T = TypeVar('T') +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request + +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 = kwargs.pop('api_version', "2022-03-01") # type: str - 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-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/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 OperationOperations(object): - """OperationOperations 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.reservations.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 OperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.AzureReservationAPI`'s + :attr:`operation` 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.OperationResponse"]: """Get operations. List all the operations. - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.OperationList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either OperationResponse or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.OperationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationList] - 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( api_version=api_version, - template_url=self.list.metadata['url'], + 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( - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -128,10 +127,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -142,8 +139,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.Capacity/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Capacity/operations"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py index 0b36a323ae2d..b9b99c472f61 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py @@ -6,270 +6,240 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request, _format_url_section + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - **kwargs: Any + subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-25") # type: 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", "2020-10-25")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "providerId": _SERIALIZER.url("provider_id", provider_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } _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, - provider_id: str, - location: 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( + subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - 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", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "providerId": _SERIALIZER.url("provider_id", provider_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } _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_update_request_initial( - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - 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", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "providerId": _SERIALIZER.url("provider_id", provider_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), } _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="PATCH", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) - - -def build_list_request( - subscription_id: str, - provider_id: str, - location: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-25") # type: str + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(subscription_id: str, provider_id: str, location: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "providerId": _SERIALIZER.url("provider_id", provider_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), } _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 QuotaOperations(object): - """QuotaOperations 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.reservations.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 QuotaOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.AzureReservationAPI`'s + :attr:`quota` 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 get( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - **kwargs: Any - ) -> "_models.CurrentQuotaLimitBase": + self, subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any + ) -> _models.CurrentQuotaLimitBase: """Get the current quota (service limit) and usage of a resource. You can use the response from the GET operation to submit quota update request. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param resource_name: The resource name for a resource provider, such as SKU name for Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. :type resource_name: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CurrentQuotaLimitBase, or the result of cls(response) + :return: CurrentQuotaLimitBase or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CurrentQuotaLimitBase"] 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', "2020-10-25") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CurrentQuotaLimitBase] - request = build_get_request( subscription_id=subscription_id, provider_id=provider_id, location=location, resource_name=resource_name, api_version=api_version, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -278,17 +248,16 @@ def get( raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - deserialized = self._deserialize('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore def _create_or_update_initial( self, @@ -296,21 +265,35 @@ def _create_or_update_initial( provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], **kwargs: Any - ) -> Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]: - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] + ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(create_quota_request, 'CurrentQuotaLimitBase') - - request = build_create_or_update_request_initial( + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop( + "cls", None + ) # type: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_quota_request, (IO, bytes)): + _content = create_quota_request + else: + _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") + + request = build_create_or_update_request( subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -318,75 +301,178 @@ def _create_or_update_initial( api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.ExceptionResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('QuotaRequestSubmitResponse201', pipeline_response) + deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + @overload + def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Union[LROPoller[_models.CurrentQuotaLimitBase], LROPoller[_models.QuotaRequestSubmitResponse201]]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: - @distributed_trace + + #. Make the Get request to get the quota information for specific resource. + #. To increase the quota, update the limit field in the response from Get request to new value. + #. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to + update the quota. + + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 CurrentQuotaLimitBase or An instance of + LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload def begin_create_or_update( self, subscription_id: str, provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: IO, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]]: + ) -> Union[LROPoller[_models.CurrentQuotaLimitBase], LROPoller[_models.QuotaRequestSubmitResponse201]]: """Create or update the quota (service limits) of a resource to the requested value. Steps: - #. - Make the Get request to get the quota information for specific resource. + #. Make the Get request to get the quota information for specific resource. + #. To increase the quota, update the limit field in the response from Get request to new value. + #. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to + update the quota. - #. - To increase the quota, update the limit field in the response from Get request to new value. + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 CurrentQuotaLimitBase or An instance of + LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ - #. - Submit the JSON to the quota request API to update the quota. + @distributed_trace + def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], + **kwargs: Any + ) -> Union[LROPoller[_models.CurrentQuotaLimitBase], LROPoller[_models.QuotaRequestSubmitResponse201]]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + + #. Make the Get request to get the quota information for specific resource. + #. To increase the quota, update the limit field in the response from Get request to new value. + #. Submit the JSON to the quota request API to update the quota. The Create quota request may be constructed as follows. The PUT operation can be used to update the quota. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param resource_name: The resource name for a resource provider, such as SKU name for Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. :type resource_name: str - :param create_quota_request: Quota requests payload. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param create_quota_request: Quota requests payload. Is either a model type or a IO type. + Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -395,23 +481,23 @@ def begin_create_or_update( :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 CurrentQuotaLimitBase or - QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase or - ~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of + LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] - 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", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CurrentQuotaLimitBase] + 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 subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -419,32 +505,37 @@ def begin_create_or_update( create_quota_request=create_quota_request, 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('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", 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': 'original-uri'}, **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": "original-uri"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore def _update_initial( self, @@ -452,21 +543,35 @@ def _update_initial( provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], **kwargs: Any - ) -> Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]: - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] + ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - _json = self._serialize.body(create_quota_request, 'CurrentQuotaLimitBase') - - request = build_update_request_initial( + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop( + "cls", None + ) # type: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(create_quota_request, (IO, bytes)): + _content = create_quota_request + else: + _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") + + request = build_update_request( subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -474,70 +579,169 @@ def _update_initial( 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.ExceptionResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('QuotaRequestSubmitResponse201', pipeline_response) + deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore - - @distributed_trace + @overload def begin_update( self, subscription_id: str, provider_id: str, location: str, resource_name: str, - create_quota_request: "_models.CurrentQuotaLimitBase", + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]]: + ) -> Union[LROPoller[_models.CurrentQuotaLimitBase], LROPoller[_models.QuotaRequestSubmitResponse201]]: """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. + • To increase the quota, update the limit field from the GET response to a new value. + • To update the quota value, submit the JSON response to the quota request API to update the + quota. + • To update the quota. use the PATCH operation. + + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 CurrentQuotaLimitBase or An instance of + LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ + @overload + def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Union[LROPoller[_models.CurrentQuotaLimitBase], LROPoller[_models.QuotaRequestSubmitResponse201]]: + """Update the quota (service limits) of this resource to the requested value. + • To get the quota information for specific resource, send a GET request. • To increase the quota, update the limit field from the GET response to a new value. + • To update the quota value, submit the JSON response to the quota request API to update the + quota. + • To update the quota. use the PATCH operation. + :param subscription_id: Azure subscription ID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 CurrentQuotaLimitBase or An instance of + LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], + **kwargs: Any + ) -> Union[LROPoller[_models.CurrentQuotaLimitBase], LROPoller[_models.QuotaRequestSubmitResponse201]]: + """Update the quota (service limits) of this resource to the requested value. + • To get the quota information for specific resource, send a GET request. + • To increase the quota, update the limit field from the GET response to a new value. • To update the quota value, submit the JSON response to the quota request API to update the quota. • To update the quota. use the PATCH operation. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param resource_name: The resource name for a resource provider, such as SKU name for Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. :type resource_name: str - :param create_quota_request: Payload for the quota request. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param create_quota_request: Payload for the quota request. Is either a model type or a IO + type. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -546,23 +750,23 @@ def begin_update( :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 CurrentQuotaLimitBase or - QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase or - ~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of + LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.CurrentQuotaLimitBase", "_models.QuotaRequestSubmitResponse201"]] - 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", "2020-10-25")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CurrentQuotaLimitBase] + 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 subscription_id=subscription_id, provider_id=provider_id, location=location, @@ -570,89 +774,90 @@ def begin_update( create_quota_request=create_quota_request, 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('CurrentQuotaLimitBase', pipeline_response) + deserialized = self._deserialize("CurrentQuotaLimitBase", 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': 'original-uri'}, **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": "original-uri"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}"} # type: ignore @distributed_trace def list( - self, - subscription_id: str, - provider_id: str, - location: str, - **kwargs: Any - ) -> Iterable["_models.QuotaLimits"]: + self, subscription_id: str, provider_id: str, location: str, **kwargs: Any + ) -> Iterable["_models.CurrentQuotaLimitBase"]: """Gets a list of current quotas (service limits) and usage for all resources. The response from the list quota operation can be leveraged to request quota updates. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either QuotaLimits or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.QuotaLimits] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CurrentQuotaLimitBase or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QuotaLimits] - cls = kwargs.pop('cls', None) # type: ClsType["_models.QuotaLimits"] 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=subscription_id, provider_id=provider_id, location=location, api_version=api_version, - template_url=self.list.metadata['url'], + 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=subscription_id, - provider_id=provider_id, - location=location, - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -666,10 +871,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -680,8 +883,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.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py index d7b364144e6a..bea0ba0c5f0b 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py @@ -8,60 +8,61 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request, _format_url_section + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - provider_id: str, - location: str, - id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-25") # type: str - accept = "application/json" +def build_get_request(subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "providerId": _SERIALIZER.url("provider_id", provider_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), - "id": _SERIALIZER.url("id", id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "id": _SERIALIZER.url("id", id, "str"), } _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_list_request( @@ -74,117 +75,111 @@ def build_list_request( skiptoken: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-25") # type: 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", "2020-10-25")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "providerId": _SERIALIZER.url("provider_id", provider_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), } _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") if filter is not None: - _query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if top is not None: - _query_parameters['$top'] = _SERIALIZER.query("top", top, 'int', minimum=1) + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=1) if skiptoken is not None: - _query_parameters['$skiptoken'] = _SERIALIZER.query("skiptoken", skiptoken, 'str') + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "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 QuotaRequestStatusOperations(object): - """QuotaRequestStatusOperations 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.reservations.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 QuotaRequestStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.AzureReservationAPI`'s + :attr:`quota_request_status` 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 get( - self, - subscription_id: str, - provider_id: str, - location: str, - id: str, - **kwargs: Any - ) -> "_models.QuotaRequestDetails": + self, subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any + ) -> _models.QuotaRequestDetails: """For the specified Azure region (location), get the details and status of the quota request by the quota request ID for the resources of the resource provider. The PUT request for the quota (service limit) returns a response with the requestId parameter. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str - :param id: Quota Request ID. + :param id: Quota Request ID. Required. :type id: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QuotaRequestDetails, or the result of cls(response) + :return: QuotaRequestDetails or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.QuotaRequestDetails - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QuotaRequestDetails"] 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 {}) - api_version = kwargs.pop('api_version', "2020-10-25") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QuotaRequestDetails] - request = build_get_request( subscription_id=subscription_id, provider_id=provider_id, location=location, id=id, api_version=api_version, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -192,15 +187,14 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ExceptionResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QuotaRequestDetails', pipeline_response) + deserialized = self._deserialize("QuotaRequestDetails", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}"} # type: ignore @distributed_trace def list( @@ -212,26 +206,24 @@ def list( top: Optional[int] = None, skiptoken: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.QuotaRequestDetailsList"]: + ) -> Iterable["_models.QuotaRequestDetails"]: """For the specified Azure region (location), subscription, and resource provider, get the history of the quota requests for the past year. To select specific quota requests, use the oData filter. - :param subscription_id: Azure subscription ID. + :param subscription_id: Azure subscription ID. Required. :type subscription_id: str - :param provider_id: Azure resource provider ID. + :param provider_id: Azure resource provider ID. Required. :type provider_id: str - :param location: Azure region. + :param location: Azure region. Required. :type location: str :param filter: .. list-table:: :header-rows: 1 * - Field - Supported operators - * - - - - |requestSubmitTime | ge, le, eq, gt, lt. Default value is None. + * - requestSubmitTime + - ge, le, eq, gt, lt. Default value is None. :type filter: str :param top: Number of records to return. Default value is None. :type top: int @@ -240,52 +232,47 @@ def list( skiptoken parameter that specifies a starting point to use for subsequent calls. Default value is None. :type skiptoken: str - :keyword api_version: Api Version. Default value is "2020-10-25". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either QuotaRequestDetailsList or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetailsList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either QuotaRequestDetails or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetails] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-25") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QuotaRequestDetailsList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.QuotaRequestDetailsList"] 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=subscription_id, provider_id=provider_id, location=location, - api_version=api_version, filter=filter, top=top, skiptoken=skiptoken, - 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( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - api_version=api_version, - filter=filter, - top=top, - skiptoken=skiptoken, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -299,10 +286,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -313,8 +298,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.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py index f4f1d8346c62..a4a06feff7a7 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py @@ -6,295 +6,293 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, List, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request, _format_url_section + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_available_scopes_request_initial( - reservation_order_id: str, - reservation_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_available_scopes_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), } _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 - ) + _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_split_request_initial( - reservation_order_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_split_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split") path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } _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 - ) + _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_merge_request_initial( - reservation_order_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_merge_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge") path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } _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 - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_request( - reservation_order_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - accept = "application/json" +def build_list_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations") + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations" + ) path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } _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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - reservation_id: str, - reservation_order_id: str, - *, - expand: Optional[str] = None, - **kwargs: Any + reservation_id: str, reservation_order_id: str, *, expand: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: 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-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, 'str'), - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } _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") if expand is not None: - _query_parameters['expand'] = _SERIALIZER.query("expand", expand, 'str') + _params["expand"] = _SERIALIZER.query("expand", expand, "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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_request_initial( - reservation_order_id: str, - reservation_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_update_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), } _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="PATCH", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_revisions_request( - reservation_id: str, - reservation_order_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - accept = "application/json" +def build_archive_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/archive", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, 'str'), - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), } _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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_unarchive_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/unarchive", + ) # pylint: disable=line-too-long + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_revisions_request(reservation_id: str, reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_all_request( @@ -307,133 +305,214 @@ def build_list_all_request( take: Optional[float] = None, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: 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-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservations") # 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") if filter is not None: - _query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if orderby is not None: - _query_parameters['$orderby'] = _SERIALIZER.query("orderby", orderby, 'str') + _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") if refresh_summary is not None: - _query_parameters['refreshSummary'] = _SERIALIZER.query("refresh_summary", refresh_summary, 'str') + _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") if skiptoken is not None: - _query_parameters['$skiptoken'] = _SERIALIZER.query("skiptoken", skiptoken, 'float') + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "float") if selected_state is not None: - _query_parameters['selectedState'] = _SERIALIZER.query("selected_state", selected_state, 'str') + _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") if take is not None: - _query_parameters['take'] = _SERIALIZER.query("take", take, 'float') + _params["take"] = _SERIALIZER.query("take", take, "float") # 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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class ReservationOperations(object): - """ReservationOperations 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 ReservationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.AzureReservationAPI`'s + :attr:`reservation` 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") def _available_scopes_initial( self, reservation_order_id: str, reservation_id: str, - body: "_models.AvailableScopeRequest", + body: Union[_models.AvailableScopeRequest, IO], **kwargs: Any - ) -> "_models.AvailableScopeProperties": - cls = kwargs.pop('cls', None) # type: ClsType["_models.AvailableScopeProperties"] + ) -> _models.AvailableScopeProperties: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableScopeProperties] - _json = self._serialize.body(body, 'AvailableScopeRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "AvailableScopeRequest") - request = build_available_scopes_request_initial( + request = build_available_scopes_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._available_scopes_initial.metadata['url'], + content=_content, + template_url=self._available_scopes_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AvailableScopeProperties', pipeline_response) + deserialized = self._deserialize("AvailableScopeProperties", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _available_scopes_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore + _available_scopes_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore + @overload + def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: _models.AvailableScopeRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Get Available Scopes for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param body: Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 AvailableScopeProperties or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Get Available Scopes for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param body: Required. + :type body: 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 AvailableScopeProperties or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_available_scopes( self, reservation_order_id: str, reservation_id: str, - body: "_models.AvailableScopeRequest", + body: Union[_models.AvailableScopeRequest, IO], **kwargs: Any - ) -> LROPoller["_models.AvailableScopeProperties"]: + ) -> LROPoller[_models.AvailableScopeProperties]: """Get Available Scopes for ``Reservation``. Get Available Scopes for ``Reservation``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param body: - :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :param body: Is either a model type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -445,119 +524,135 @@ def begin_available_scopes( :return: An instance of LROPoller that returns either AvailableScopeProperties or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.AvailableScopeProperties"] - 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", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableScopeProperties] + 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._available_scopes_initial( + raw_result = self._available_scopes_initial( # type: ignore reservation_order_id=reservation_order_id, reservation_id=reservation_id, body=body, 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('AvailableScopeProperties', pipeline_response) + deserialized = self._deserialize("AvailableScopeProperties", 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, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_available_scopes.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore + begin_available_scopes.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes"} # type: ignore def _split_initial( - self, - reservation_order_id: str, - body: "_models.SplitRequest", - **kwargs: Any - ) -> Optional[List["_models.ReservationResponse"]]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional[List["_models.ReservationResponse"]]] + self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any + ) -> Optional[List[_models.ReservationResponse]]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[List[_models.ReservationResponse]]] - _json = self._serialize.body(body, 'SplitRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "SplitRequest") - request = build_split_request_initial( + request = build_split_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._split_initial.metadata['url'], + content=_content, + template_url=self._split_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _split_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore + _split_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore - - @distributed_trace + @overload def begin_split( self, reservation_order_id: str, - body: "_models.SplitRequest", + body: _models.SplitRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[List["_models.ReservationResponse"]]: + ) -> LROPoller[List[_models.ReservationResponse]]: """Split the ``Reservation``. Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed to Split a reservation item. + :param body: Information needed to Split a reservation item. Required. :type body: ~azure.mgmt.reservations.models.SplitRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -570,119 +665,198 @@ def begin_split( of cls(response) :rtype: ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[List["_models.ReservationResponse"]] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_split( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: 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 list of ReservationResponse or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_split( + self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Is either a model type or a IO + type. Required. + :type body: ~azure.mgmt.reservations.models.SplitRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either list of ReservationResponse or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[List[_models.ReservationResponse]] + 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._split_initial( + raw_result = self._split_initial( # type: ignore reservation_order_id=reservation_order_id, body=body, 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('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", 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': 'location'}, **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, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_split.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore + begin_split.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} # type: ignore def _merge_initial( - self, - reservation_order_id: str, - body: "_models.MergeRequest", - **kwargs: Any - ) -> Optional[List["_models.ReservationResponse"]]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional[List["_models.ReservationResponse"]]] + self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any + ) -> Optional[List[_models.ReservationResponse]]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[List[_models.ReservationResponse]]] - _json = self._serialize.body(body, 'MergeRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "MergeRequest") - request = build_merge_request_initial( + request = build_merge_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._merge_initial.metadata['url'], + content=_content, + template_url=self._merge_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _merge_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore - + _merge_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore - @distributed_trace + @overload def begin_merge( self, reservation_order_id: str, - body: "_models.MergeRequest", + body: _models.MergeRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[List["_models.ReservationResponse"]]: + ) -> LROPoller[List[_models.ReservationResponse]]: """Merges two ``Reservation``\ s. Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s being merged must have same properties. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. + :param body: Information needed for commercial request for a reservation. Required. :type body: ~azure.mgmt.reservations.models.MergeRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -695,97 +869,162 @@ def begin_merge( of cls(response) :rtype: ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[List["_models.ReservationResponse"]] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_merge( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``\ s. + + Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s + being merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: 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 list of ReservationResponse or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_merge( + self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``\ s. + + Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s + being merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Is either a model + type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.MergeRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either list of ReservationResponse or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[List[_models.ReservationResponse]] + 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._merge_initial( + raw_result = self._merge_initial( # type: ignore reservation_order_id=reservation_order_id, body=body, 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('[ReservationResponse]', pipeline_response) + deserialized = self._deserialize("[ReservationResponse]", 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': 'location'}, **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, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_merge.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore + begin_merge.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} # type: ignore @distributed_trace - def list( - self, - reservation_order_id: str, - **kwargs: Any - ) -> Iterable["_models.ReservationList"]: + def list(self, reservation_order_id: str, **kwargs: Any) -> Iterable["_models.ReservationResponse"]: """Get ``Reservation``\ s in a given reservation Order. List ``Reservation``\ s within a single ``ReservationOrder``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationResponse or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationList"] 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( reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list.metadata['url'], + 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( - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -799,10 +1038,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -813,62 +1050,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': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations"} # type: ignore @distributed_trace def get( - self, - reservation_id: str, - reservation_order_id: str, - expand: Optional[str] = None, - **kwargs: Any - ) -> "_models.ReservationResponse": + self, reservation_id: str, reservation_order_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationResponse: """Get ``Reservation`` details. Get specific ``Reservation`` details. - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param expand: Supported value of this query is renewProperties. Default value is None. :type expand: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationResponse, or the result of cls(response) + :return: ReservationResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.ReservationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationResponse"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationResponse] - request = build_get_request( reservation_id=reservation_id, reservation_order_id=reservation_order_id, - api_version=api_version, expand=expand, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -876,89 +1110,100 @@ def get( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ReservationResponse', pipeline_response) + deserialized = self._deserialize("ReservationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore - + get.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore def _update_initial( - self, - reservation_order_id: str, - reservation_id: str, - parameters: "_models.Patch", - **kwargs: Any - ) -> Optional["_models.ReservationResponse"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ReservationResponse"]] + self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any + ) -> Optional[_models.ReservationResponse]: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ReservationResponse]] - _json = self._serialize.body(parameters, 'Patch') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Patch") - request = build_update_request_initial( + request = build_update_request( reservation_order_id=reservation_order_id, reservation_id=reservation_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ReservationResponse', pipeline_response) + deserialized = self._deserialize("ReservationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore + _update_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore - - @distributed_trace + @overload def begin_update( self, reservation_order_id: str, reservation_id: str, - parameters: "_models.Patch", + parameters: _models.Patch, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.ReservationResponse"]: + ) -> LROPoller[_models.ReservationResponse]: """Updates a ``Reservation``. Updates the applied scopes of the ``Reservation``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param parameters: Information needed to patch a reservation item. + :param parameters: Information needed to patch a reservation item. Required. :type parameters: ~azure.mgmt.reservations.models.Patch - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -970,103 +1215,288 @@ def begin_update( :return: An instance of LROPoller that returns either ReservationResponse or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationResponse"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. 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 ReservationResponse or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any + ) -> LROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.reservations.models.Patch or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ReservationResponse or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationResponse] + 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 reservation_order_id=reservation_order_id, reservation_id=reservation_id, 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('ReservationResponse', pipeline_response) + deserialized = self._deserialize("ReservationResponse", 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, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore + begin_update.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}"} # type: ignore + + @distributed_trace + def archive( # pylint: disable=inconsistent-return-statements + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> None: + """Archive a ``Reservation``. + + Archiving a ``Reservation`` moves it to ``Archived`` state. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_archive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + template_url=self.archive.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + archive.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/archive"} # type: ignore + + @distributed_trace + def unarchive( # pylint: disable=inconsistent-return-statements + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> None: + """Unarchive a ``Reservation``. + + Unarchiving a ``Reservation`` moves it to the state it was before archiving. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the Reservation Item. Required. + :type reservation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_unarchive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + template_url=self.unarchive.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + unarchive.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/unarchive"} # type: ignore @distributed_trace def list_revisions( - self, - reservation_id: str, - reservation_order_id: str, - **kwargs: Any - ) -> Iterable["_models.ReservationList"]: + self, reservation_id: str, reservation_order_id: str, **kwargs: Any + ) -> Iterable["_models.ReservationResponse"]: """Get ``Reservation`` revisions. List of all the revisions for the ``Reservation``. - :param reservation_id: Id of the Reservation Item. + :param reservation_id: Id of the Reservation Item. Required. :type reservation_id: str - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationResponse or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationList"] 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_revisions_request( reservation_id=reservation_id, reservation_order_id=reservation_order_id, api_version=api_version, - template_url=self.list_revisions.metadata['url'], + template_url=self.list_revisions.metadata["url"], + 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_revisions_request( - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -1080,10 +1510,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -1094,11 +1522,9 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_revisions.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions"} # type: ignore + list_revisions.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions"} # type: ignore @distributed_trace def list_all( @@ -1110,7 +1536,7 @@ def list_all( selected_state: Optional[str] = None, take: Optional[float] = None, **kwargs: Any - ) -> Iterable["_models.ReservationsListResult"]: + ) -> Iterable["_models.ReservationResponse"]: """List the reservations and the roll up counts of reservations group by provisioning states that the user has access to in the current tenant. @@ -1133,52 +1559,47 @@ def list_all( :type selected_state: str :param take: To number of reservations to return. Default value is None. :type take: float - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationsListResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationResponse or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationsListResult"] 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_all_request( - api_version=api_version, filter=filter, orderby=orderby, refresh_summary=refresh_summary, skiptoken=skiptoken, selected_state=selected_state, take=take, - template_url=self.list_all.metadata['url'], + api_version=api_version, + template_url=self.list_all.metadata["url"], + 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_all_request( - api_version=api_version, - filter=filter, - orderby=orderby, - refresh_summary=refresh_summary, - skiptoken=skiptoken, - selected_state=selected_state, - take=take, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -1192,10 +1613,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -1206,8 +1625,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_all.metadata = {'url': "/providers/Microsoft.Capacity/reservations"} # type: ignore + list_all.metadata = {"url": "/providers/Microsoft.Capacity/reservations"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py index 7fbdc80817b7..21b1a5f1655d 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py @@ -6,271 +6,273 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request, _format_url_section + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_calculate_request( - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_calculate_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-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/calculatePrice") # 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 - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str +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-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders") # 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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_purchase_request_initial( - reservation_order_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_purchase_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}") path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } _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 - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + +def build_get_request(reservation_order_id: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -def build_get_request( - reservation_order_id: str, - *, - expand: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}") path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } _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") if expand is not None: - _query_parameters['$expand'] = _SERIALIZER.query("expand", expand, 'str') + _params["$expand"] = _SERIALIZER.query("expand", expand, "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 - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_change_directory_request( - reservation_order_id: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] +def build_change_directory_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory") + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory" + ) path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } _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 - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -class ReservationOrderOperations(object): - """ReservationOrderOperations 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 ReservationOrderOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.reservations.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.reservations.AzureReservationAPI`'s + :attr:`reservation_order` 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 calculate( - self, - body: "_models.PurchaseRequest", - **kwargs: Any - ) -> "_models.CalculatePriceResponse": + self, body: _models.PurchaseRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: """Calculate price for a ``ReservationOrder``. Calculate price for placing a ``ReservationOrder``. - :param body: Information needed for calculate or purchase reservation. + :param body: Information needed for calculate or purchase reservation. Required. :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CalculatePriceResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def calculate( + self, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: Information needed for calculate or purchase reservation. Required. + :type body: 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: CalculatePriceResponse, or the result of cls(response) + :return: CalculatePriceResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def calculate(self, body: Union[_models.PurchaseRequest, IO], **kwargs: Any) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: Information needed for calculate or purchase reservation. Is either a model type + or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: CalculatePriceResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CalculatePriceResponse"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CalculatePriceResponse] - _json = self._serialize.body(body, 'PurchaseRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "PurchaseRequest") request = build_calculate_request( api_version=api_version, content_type=content_type, json=_json, - template_url=self.calculate.metadata['url'], + content=_content, + template_url=self.calculate.metadata["url"], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -278,59 +280,57 @@ def calculate( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CalculatePriceResponse', pipeline_response) + deserialized = self._deserialize("CalculatePriceResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - calculate.metadata = {'url': "/providers/Microsoft.Capacity/calculatePrice"} # type: ignore - + calculate.metadata = {"url": "/providers/Microsoft.Capacity/calculatePrice"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.ReservationOrderList"]: + def list(self, **kwargs: Any) -> Iterable["_models.ReservationOrderResponse"]: """Get all ``ReservationOrder``\ s. List of all the ``ReservationOrder``\ s that the user has access to in the current tenant. - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationOrderList or the result of + :return: An iterator like instance of either ReservationOrderResponse or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationOrderList] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderList] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderList"] 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( api_version=api_version, - template_url=self.list.metadata['url'], + 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( - api_version=api_version, - template_url=next_link, - ) + request = HttpRequest("GET", next_link) 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 @@ -344,10 +344,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -358,82 +356,93 @@ 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.Capacity/reservationOrders"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders"} # type: ignore def _purchase_initial( - self, - reservation_order_id: str, - body: "_models.PurchaseRequest", - **kwargs: Any - ) -> "_models.ReservationOrderResponse": - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderResponse"] + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any + ) -> _models.ReservationOrderResponse: 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderResponse] - _json = self._serialize.body(body, 'PurchaseRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "PurchaseRequest") - request = build_purchase_request_initial( + request = build_purchase_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._purchase_initial.metadata['url'], + content=_content, + template_url=self._purchase_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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 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.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _purchase_initial.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore - + _purchase_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore - @distributed_trace + @overload def begin_purchase( self, reservation_order_id: str, - body: "_models.PurchaseRequest", + body: _models.PurchaseRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.ReservationOrderResponse"]: + ) -> LROPoller[_models.ReservationOrderResponse]: """Purchase ``ReservationOrder``. Purchase ``ReservationOrder`` and create resource under the specified URI. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. + :param body: Information needed for calculate or purchase reservation. Required. :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -445,96 +454,160 @@ def begin_purchase( :return: An instance of LROPoller that returns either ReservationOrderResponse or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderResponse"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_purchase( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: 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 ReservationOrderResponse or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_purchase( + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Is either a model type + or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ReservationOrderResponse or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderResponse] + 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._purchase_initial( + raw_result = self._purchase_initial( # type: ignore reservation_order_id=reservation_order_id, body=body, 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('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", 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': 'location'}, **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, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_purchase.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore + begin_purchase.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore @distributed_trace def get( - self, - reservation_order_id: str, - expand: Optional[str] = None, - **kwargs: Any - ) -> "_models.ReservationOrderResponse": + self, reservation_order_id: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationOrderResponse: """Get a specific ``ReservationOrder``. Get the details of the ``ReservationOrder``. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param expand: May be used to expand the planInformation. Default value is None. :type expand: str - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationOrderResponse, or the result of cls(response) + :return: ReservationOrderResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.ReservationOrderResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationOrderResponse"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationOrderResponse] - request = build_get_request( reservation_order_id=reservation_order_id, - api_version=api_version, expand=expand, - template_url=self.get.metadata['url'], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -542,66 +615,126 @@ def get( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ReservationOrderResponse', pipeline_response) + deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore + get.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} # type: ignore - - @distributed_trace + @overload def change_directory( self, reservation_order_id: str, - body: "_models.ChangeDirectoryRequest", + body: _models.ChangeDirectoryRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.ChangeDirectoryResponse": + ) -> _models.ChangeDirectoryResponse: """Change directory of ``ReservationOrder``. Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified tenant id. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. + :param body: Information needed to change directory of reservation order. Required. :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest - :keyword api_version: Api Version. Default value is "2022-03-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChangeDirectoryResponse, or the result of cls(response) + :return: ChangeDirectoryResponse or the result of cls(response) :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def change_directory( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: 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: ChangeDirectoryResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def change_directory( + self, reservation_order_id: str, body: Union[_models.ChangeDirectoryRequest, IO], **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Is either a model + type or a IO type. Required. + :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: ChangeDirectoryResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ChangeDirectoryResponse"] 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 {}) - api_version = kwargs.pop('api_version', "2022-03-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ChangeDirectoryResponse] - _json = self._serialize.body(body, 'ChangeDirectoryRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ChangeDirectoryRequest") request = build_change_directory_request( reservation_order_id=reservation_order_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.change_directory.metadata['url'], + content=_content, + template_url=self.change_directory.metadata["url"], + 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -609,12 +742,11 @@ def change_directory( error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ChangeDirectoryResponse', pipeline_response) + deserialized = self._deserialize("ChangeDirectoryResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - change_directory.metadata = {'url': "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory"} # type: ignore - + change_directory.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory"} # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py new file mode 100644 index 000000000000..ac22a2f6b158 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py @@ -0,0 +1,208 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import MixinABC, _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_post_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return") + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ReturnOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.AzureReservationAPI`'s + :attr:`return_operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def post( + self, + reservation_order_id: str, + body: _models.RefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RefundResponse: + """Return a reservation. + + Return a reservation. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.RefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def post( + self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RefundResponse: + """Return a reservation. + + Return a reservation. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: 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: RefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.RefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def post( + self, reservation_order_id: str, body: Union[_models.RefundRequest, IO], **kwargs: Any + ) -> _models.RefundResponse: + """Return a reservation. + + Return a reservation. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Is either a model type or a IO type. + Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: RefundResponse or the result of cls(response) + :rtype: ~azure.mgmt.reservations.models.RefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.RefundResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = self._serialize.body(body, "RefundRequest") + + request = build_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.post.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = self._deserialize("RefundResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return"} # type: ignore