diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json b/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json index 8041e01d515b..6fdb6cd40d0d 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json +++ b/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.4.5", + "autorest": "3.8.4", "use": [ - "@autorest/python@5.8.4", - "@autorest/modelerfour@4.19.2" + "@autorest/python@6.1.6", + "@autorest/modelerfour@4.23.5" ], - "commit": "74efe54fbc55c91a1d9213afbb2723747acfddf9", + "commit": "a2b6c03a2bfd8ecc1d30d3710c12f9a970a18fac", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/cost-management/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --track2 --use=@autorest/python@5.8.4 --use=@autorest/modelerfour@4.19.2 --version=3.4.5", + "autorest_command": "autorest specification/cost-management/resource-manager/readme.md --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.1.6 --use=@autorest/modelerfour@4.23.5 --version=3.8.4 --version-tolerant=False", "readme": "specification/cost-management/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py index 0e26ee2701fe..04ace69e34c8 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['CostManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["CostManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py index 0cd20f8ef97a..ccf100de35ec 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py @@ -6,60 +6,53 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class CostManagementClientConfiguration(Configuration): +class CostManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for CostManagementClient. 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, # type: "TokenCredential" - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: + super(CostManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") - super(CostManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential - self.api_version = "2019-11-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-costmanagement/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-costmanagement/{}".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 = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py index 521cb5222a88..b182f43af98c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py @@ -6,36 +6,41 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from ._configuration import CostManagementClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + AlertsOperations, + DimensionsOperations, + ExportsOperations, + ForecastOperations, + GenerateCostDetailsReportOperations, + GenerateDetailedCostReportOperationResultsOperations, + GenerateDetailedCostReportOperationStatusOperations, + GenerateDetailedCostReportOperations, + GenerateReservationDetailsReportOperations, + Operations, + QueryOperations, + ViewsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import CostManagementClientConfiguration -from .operations import SettingsOperations -from .operations import ViewsOperations -from .operations import AlertsOperations -from .operations import ForecastOperations -from .operations import DimensionsOperations -from .operations import QueryOperations -from .operations import GenerateReservationDetailsReportOperations -from .operations import Operations -from .operations import ExportsOperations -from . import models -class CostManagementClient(object): +class CostManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """CostManagementClient. - :ivar settings: SettingsOperations operations - :vartype settings: azure.mgmt.costmanagement.operations.SettingsOperations + :ivar generate_cost_details_report: GenerateCostDetailsReportOperations operations + :vartype generate_cost_details_report: + azure.mgmt.costmanagement.operations.GenerateCostDetailsReportOperations :ivar views: ViewsOperations operations :vartype views: azure.mgmt.costmanagement.operations.ViewsOperations :ivar alerts: AlertsOperations operations @@ -46,68 +51,87 @@ class CostManagementClient(object): :vartype dimensions: azure.mgmt.costmanagement.operations.DimensionsOperations :ivar query: QueryOperations operations :vartype query: azure.mgmt.costmanagement.operations.QueryOperations - :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations operations - :vartype generate_reservation_details_report: azure.mgmt.costmanagement.operations.GenerateReservationDetailsReportOperations + :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations + operations + :vartype generate_reservation_details_report: + azure.mgmt.costmanagement.operations.GenerateReservationDetailsReportOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.costmanagement.operations.Operations :ivar exports: ExportsOperations operations :vartype exports: azure.mgmt.costmanagement.operations.ExportsOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar generate_detailed_cost_report: GenerateDetailedCostReportOperations operations + :vartype generate_detailed_cost_report: + azure.mgmt.costmanagement.operations.GenerateDetailedCostReportOperations + :ivar generate_detailed_cost_report_operation_results: + GenerateDetailedCostReportOperationResultsOperations operations + :vartype generate_detailed_cost_report_operation_results: + azure.mgmt.costmanagement.operations.GenerateDetailedCostReportOperationResultsOperations + :ivar generate_detailed_cost_report_operation_status: + GenerateDetailedCostReportOperationStatusOperations operations + :vartype generate_detailed_cost_report_operation_status: + azure.mgmt.costmanagement.operations.GenerateDetailedCostReportOperationStatusOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( - self, - credential, # type: "TokenCredential" - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = CostManagementClientConfiguration(credential, **kwargs) + self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + ) -> None: + self._config = CostManagementClientConfiguration(credential=credential, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.settings = SettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.views = ViewsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.alerts = AlertsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.forecast = ForecastOperations( - self._client, self._config, self._serialize, self._deserialize) - self.dimensions = DimensionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.query = QueryOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.generate_cost_details_report = GenerateCostDetailsReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) + self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.exports = ExportsOperations( - self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + self._client, self._config, self._serialize, self._deserialize + ) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.exports = ExportsOperations(self._client, self._config, self._serialize, self._deserialize) + self.generate_detailed_cost_report = GenerateDetailedCostReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_results = GenerateDetailedCostReportOperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_status = GenerateDetailedCostReportOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - http_request.url = self._client.format_url(http_request.url) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_metadata.json b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_metadata.json deleted file mode 100644 index 1e323f28f6ac..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_metadata.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "chosen_version": "2019-11-01", - "total_api_version_list": ["2019-11-01"], - "client": { - "name": "CostManagementClient", - "filename": "_cost_management_client", - "description": "CostManagementClient.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, - "azure_arm": true, - "has_lro_operations": true, - "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"CostManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"CostManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - } - }, - "async": { - "credential": { - "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", - "required": true - } - }, - "constant": { - }, - "call": "credential", - "service_client_specific": { - "sync": { - "api_version": { - "signature": "api_version=None, # type: Optional[str]", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url=None, # type: Optional[str]", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: Optional[str] = None,", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "settings": "SettingsOperations", - "views": "ViewsOperations", - "alerts": "AlertsOperations", - "forecast": "ForecastOperations", - "dimensions": "DimensionsOperations", - "query": "QueryOperations", - "generate_reservation_details_report": "GenerateReservationDetailsReportOperations", - "operations": "Operations", - "exports": "ExportsOperations" - } -} \ No newline at end of file diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py new file mode 100644 index 000000000000..9aad73fc743e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py index cac9f5d10f8b..e5754a47ce68 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "3.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py index 7dec206f98a6..05984fcaff95 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._cost_management_client import CostManagementClient -__all__ = ['CostManagementClient'] + +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__ = ["CostManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py index 22c0705a007a..88400caadac1 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,43 +19,37 @@ from azure.core.credentials_async import AsyncTokenCredential -class CostManagementClientConfiguration(Configuration): +class CostManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for CostManagementClient. 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(CostManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") - super(CostManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential - self.api_version = "2019-11-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-costmanagement/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-costmanagement/{}".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 = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py index ab4f0f5bdab7..8bf1102eab0e 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py @@ -6,34 +6,41 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from .._serialization import Deserializer, Serializer +from ._configuration import CostManagementClientConfiguration +from .operations import ( + AlertsOperations, + DimensionsOperations, + ExportsOperations, + ForecastOperations, + GenerateCostDetailsReportOperations, + GenerateDetailedCostReportOperationResultsOperations, + GenerateDetailedCostReportOperationStatusOperations, + GenerateDetailedCostReportOperations, + GenerateReservationDetailsReportOperations, + Operations, + QueryOperations, + ViewsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import CostManagementClientConfiguration -from .operations import SettingsOperations -from .operations import ViewsOperations -from .operations import AlertsOperations -from .operations import ForecastOperations -from .operations import DimensionsOperations -from .operations import QueryOperations -from .operations import GenerateReservationDetailsReportOperations -from .operations import Operations -from .operations import ExportsOperations -from .. import models - -class CostManagementClient(object): +class CostManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """CostManagementClient. - :ivar settings: SettingsOperations operations - :vartype settings: azure.mgmt.costmanagement.aio.operations.SettingsOperations + :ivar generate_cost_details_report: GenerateCostDetailsReportOperations operations + :vartype generate_cost_details_report: + azure.mgmt.costmanagement.aio.operations.GenerateCostDetailsReportOperations :ivar views: ViewsOperations operations :vartype views: azure.mgmt.costmanagement.aio.operations.ViewsOperations :ivar alerts: AlertsOperations operations @@ -44,66 +51,87 @@ class CostManagementClient(object): :vartype dimensions: azure.mgmt.costmanagement.aio.operations.DimensionsOperations :ivar query: QueryOperations operations :vartype query: azure.mgmt.costmanagement.aio.operations.QueryOperations - :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations operations - :vartype generate_reservation_details_report: azure.mgmt.costmanagement.aio.operations.GenerateReservationDetailsReportOperations + :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations + operations + :vartype generate_reservation_details_report: + azure.mgmt.costmanagement.aio.operations.GenerateReservationDetailsReportOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.costmanagement.aio.operations.Operations :ivar exports: ExportsOperations operations :vartype exports: azure.mgmt.costmanagement.aio.operations.ExportsOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar generate_detailed_cost_report: GenerateDetailedCostReportOperations operations + :vartype generate_detailed_cost_report: + azure.mgmt.costmanagement.aio.operations.GenerateDetailedCostReportOperations + :ivar generate_detailed_cost_report_operation_results: + GenerateDetailedCostReportOperationResultsOperations operations + :vartype generate_detailed_cost_report_operation_results: + azure.mgmt.costmanagement.aio.operations.GenerateDetailedCostReportOperationResultsOperations + :ivar generate_detailed_cost_report_operation_status: + GenerateDetailedCostReportOperationStatusOperations operations + :vartype generate_detailed_cost_report_operation_status: + azure.mgmt.costmanagement.aio.operations.GenerateDetailedCostReportOperationStatusOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( - self, - credential: "AsyncTokenCredential", - base_url: Optional[str] = None, - **kwargs: Any + self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = CostManagementClientConfiguration(credential, **kwargs) + self._config = CostManagementClientConfiguration(credential=credential, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.settings = SettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.views = ViewsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.alerts = AlertsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.forecast = ForecastOperations( - self._client, self._config, self._serialize, self._deserialize) - self.dimensions = DimensionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.query = QueryOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.generate_cost_details_report = GenerateCostDetailsReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) + self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.exports = ExportsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.exports = ExportsOperations(self._client, self._config, self._serialize, self._deserialize) + self.generate_detailed_cost_report = GenerateDetailedCostReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_results = GenerateDetailedCostReportOperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_status = GenerateDetailedCostReportOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - http_request.url = self._client.format_url(http_request.url) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py index c70a4cb564cb..56106cebd774 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._settings_operations import SettingsOperations +from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations from ._views_operations import ViewsOperations from ._alerts_operations import AlertsOperations from ._forecast_operations import ForecastOperations @@ -15,15 +15,31 @@ from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations from ._operations import Operations from ._exports_operations import ExportsOperations +from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations +from ._generate_detailed_cost_report_operation_results_operations import ( + GenerateDetailedCostReportOperationResultsOperations, +) +from ._generate_detailed_cost_report_operation_status_operations import ( + GenerateDetailedCostReportOperationStatusOperations, +) + +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__ = [ - 'SettingsOperations', - 'ViewsOperations', - 'AlertsOperations', - 'ForecastOperations', - 'DimensionsOperations', - 'QueryOperations', - 'GenerateReservationDetailsReportOperations', - 'Operations', - 'ExportsOperations', + "GenerateCostDetailsReportOperations", + "ViewsOperations", + "AlertsOperations", + "ForecastOperations", + "DimensionsOperations", + "QueryOperations", + "GenerateReservationDetailsReportOperations", + "Operations", + "ExportsOperations", + "GenerateDetailedCostReportOperations", + "GenerateDetailedCostReportOperationResultsOperations", + "GenerateDetailedCostReportOperationStatusOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py index 216d5ebc7b21..f0a8affa6c34 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,46 +6,57 @@ # 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, Generic, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._alerts_operations import ( + build_dismiss_request, + build_get_request, + build_list_external_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AlertsOperations: - """AlertsOperations 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 AlertsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`alerts` 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 list( - self, - scope: str, - **kwargs: Any - ) -> "_models.AlertsResult": + @distributed_trace_async + async def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: """Lists the alerts for scope defined. :param scope: The scope associated with alerts operations. This includes @@ -62,59 +74,59 @@ async def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_list_request( + scope=scope, + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts'} # type: ignore - async def get( - self, - scope: str, - alert_id: str, - **kwargs: Any - ) -> "_models.Alert": + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: """Gets the alert for the scope by alert ID. :param scope: The scope associated with alerts operations. This includes @@ -132,63 +144,70 @@ async def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @overload async def dismiss( self, scope: str, alert_id: str, - parameters: "_models.DismissAlertPayload", + parameters: _models.DismissAlertPayload, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Alert": + ) -> _models.Alert: """Dismisses the specified alert. :param scope: The scope associated with alerts operations. This includes @@ -206,120 +225,215 @@ async def dismiss( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str - :param parameters: Parameters supplied to the Dismiss Alert operation. + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def dismiss( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def dismiss( + self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO], **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.dismiss.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'DismissAlertPayload') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.Alert] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "DismissAlertPayload") + + request = build_dismiss_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.dismiss.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - dismiss.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + dismiss.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @distributed_trace_async async def list_external( self, external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], external_cloud_provider_id: str, **kwargs: Any - ) -> "_models.AlertsResult": + ) -> _models.AlertsResult: """Lists the Alerts for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list_external.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_list_external_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + template_url=self.list_external.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 + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_external.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts'} # type: ignore + + list_external.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py index 090f2e992e2d..d53b75682105 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,52 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union 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, HttpRequest +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._dimensions_operations import build_by_external_cloud_provider_type_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DimensionsOperations: - """DimensionsOperations 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 DimensionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`dimensions` 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, scope: str, @@ -49,7 +60,7 @@ def list( skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.DimensionsListResult"]: + ) -> AsyncIterable["_models.Dimension"]: """Lists the dimensions by the defined scope. :param scope: The scope associated with dimension operations. This includes @@ -67,66 +78,68 @@ def list( 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + 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) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -135,21 +148,23 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/dimensions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/dimensions"} # type: ignore + + @distributed_trace def by_external_cloud_provider_type( self, external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], @@ -159,75 +174,80 @@ def by_external_cloud_provider_type( skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.DimensionsListResult"]: + ) -> AsyncIterable["_models.Dimension"]: """Lists the dimensions by the external cloud provider type. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -236,17 +256,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(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]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py index 2f3497eee08b..674fa8681ba9 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,49 +6,62 @@ # 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, Generic, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._exports_operations import ( + build_create_or_update_request, + build_delete_request, + build_execute_request, + build_get_execution_history_request, + build_get_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ExportsOperations: - """ExportsOperations 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 ExportsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`exports` 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 list( - self, - scope: str, - **kwargs: Any - ) -> "_models.ExportListResult": + @distributed_trace_async + async def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _models.ExportListResult: """The operation to list all exports at the given scope. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -62,62 +76,67 @@ async def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last execution of each export. + Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportListResult, or the result of cls(response) + :return: ExportListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportListResult] + + request = build_list_request( + scope=scope, + expand=expand, + 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) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportListResult', pipeline_response) + deserialized = self._deserialize("ExportListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports'} # type: ignore - async def get( - self, - scope: str, - export_name: str, - **kwargs: Any - ) -> "_models.Export": + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.Export: """The operation to get the export for the defined scope by export name. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -132,68 +151,80 @@ async def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last 10 executions of the export. + Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Export] + + request = build_get_request( + scope=scope, + export_name=export_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @overload async def create_or_update( self, scope: str, export_name: str, - parameters: "_models.Export", + parameters: _models.Export, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Export": + ) -> _models.Export: """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -208,76 +239,165 @@ async def create_or_update( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str - :param parameters: Parameters supplied to the CreateOrUpdate Export operation. + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.Export + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, scope: str, export_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, scope: str, export_name: str, parameters: Union[_models.Export, IO], **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Export or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Export') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.Export] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Export") + + request = build_create_or_update_request( + scope=scope, + export_name=export_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore - async def delete( - self, - scope: str, - export_name: str, - **kwargs: Any + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any ) -> None: """The operation to delete a export. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -292,62 +412,63 @@ async def delete( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore - async def execute( - self, - scope: str, - export_name: str, - **kwargs: Any + @distributed_trace_async + async def execute( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any ) -> None: - """The operation to execute a export. + """The operation to execute an export. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -362,62 +483,63 @@ async def execute( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.execute.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_execute_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.execute.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - execute.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run'} # type: ignore + execute.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run"} # type: ignore + @distributed_trace_async async def get_execution_history( - self, - scope: str, - export_name: str, - **kwargs: Any - ) -> "_models.ExportExecutionListResult": - """The operation to get the execution history of an export for the defined scope by export name. + self, scope: str, export_name: str, **kwargs: Any + ) -> _models.ExportExecutionListResult: + """The operation to get the execution history of an export for the defined scope and export name. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -432,52 +554,56 @@ async def get_execution_history( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportExecutionListResult, or the result of cls(response) + :return: ExportExecutionListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportExecutionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_execution_history.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportExecutionListResult] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_execution_history_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.get_execution_history.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 + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportExecutionListResult', pipeline_response) + deserialized = self._deserialize("ExportExecutionListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_execution_history.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory'} # type: ignore + + get_execution_history.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py index 8524f06621a5..4e43be9072b2 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,48 +6,60 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +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._forecast_operations import build_external_cloud_provider_usage_request, build_usage_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ForecastOperations: - """ForecastOperations 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 ForecastOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`forecast` 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") + @overload async def usage( self, scope: str, - parameters: "_models.ForecastDefinition", + parameters: _models.ForecastDefinition, filter: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> Optional["_models.QueryResult"]: + ) -> Optional[_models.ForecastResult]: """Lists the forecast charges for scope defined. :param scope: The scope associated with forecast operations. This includes @@ -64,140 +77,334 @@ async def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: 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: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def usage( + self, + scope: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def usage( + self, scope: str, parameters: Union[_models.ForecastDefinition, IO], filter: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.ForecastResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_usage_request( + scope=scope, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.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, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/forecast'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/forecast"} # type: ignore + + @overload async def external_cloud_provider_usage( self, external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], external_cloud_provider_id: str, - parameters: "_models.ForecastDefinition", + parameters: _models.ForecastDefinition, filter: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.QueryResult": + ) -> _models.ForecastResult: """Lists the forecast charges for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: 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: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: Union[_models.ForecastDefinition, IO], + filter: Optional[str] = None, + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.external_cloud_provider_usage.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.ForecastResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_external_cloud_provider_usage_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.external_cloud_provider_usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - external_cloud_provider_usage.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast'} # type: ignore + + external_cloud_provider_usage.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py new file mode 100644 index 000000000000..8f8859693b4d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py @@ -0,0 +1,456 @@ +# 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, 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._generate_cost_details_report_operations import ( + build_create_operation_request, + build_get_operation_results_request, +) + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateCostDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_cost_details_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + 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-05-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.CostDetailsOperationResults]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateCostDetailsReportRequestDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateCostDetailsReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if response.status_code == 202: + 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 + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + @overload + async def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateCostDetailsReportRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :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-05-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.CostDetailsOperationResults] + 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_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + async def _get_operation_results_initial( + self, scope: str, operation_id: str, **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + 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-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CostDetailsOperationResults]] + + request = build_get_operation_results_request( + scope=scope, + operation_id=operation_id, + api_version=api_version, + template_url=self._get_operation_results_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _get_operation_results_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore + + @distributed_trace_async + async def begin_get_operation_results( + self, scope: str, operation_id: str, **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """Get the result of the specified operation. This link is provided in the CostDetails creation + request response Location header. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param operation_id: The target operation Id. Required. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CostDetailsOperationResults] + 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._get_operation_results_initial( # type: ignore + scope=scope, + operation_id=operation_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_get_operation_results.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py new file mode 100644 index 000000000000..d7e2295b4aff --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py @@ -0,0 +1,126 @@ +# 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, Optional, TypeVar + +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._generate_detailed_cost_report_operation_results_operations import build_get_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateDetailedCostReportOperationResultsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_results` 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") + + @distributed_trace_async + async def get( + self, operation_id: str, scope: str, **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + """Get the result of the specified operation. This link is provided in the + GenerateDetailedCostReport creation request response header. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GenerateDetailedCostReportOperationResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult or 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", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py new file mode 100644 index 000000000000..e0ee194d4214 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py @@ -0,0 +1,124 @@ +# 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, Optional, TypeVar + +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._generate_detailed_cost_report_operation_status_operations import build_get_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateDetailedCostReportOperationStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_status` 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") + + @distributed_trace_async + async def get( + self, operation_id: str, scope: str, **kwargs: Any + ) -> _models.GenerateDetailedCostReportOperationStatuses: + """Get the status of the specified operation. This link is provided in the + GenerateDetailedCostReport creation request response header. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GenerateDetailedCostReportOperationStatuses or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationStatuses + :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", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationStatuses] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py new file mode 100644 index 000000000000..8fb6c305fd26 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py @@ -0,0 +1,311 @@ +# 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, 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._generate_detailed_cost_report_operations import build_create_operation_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateDetailedCostReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_detailed_cost_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + 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", "2021-10-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.GenerateDetailedCostReportOperationResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateDetailedCostReportDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateDetailedCostReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Azure-Consumption-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-Consumption-AsyncOperation") + ) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore + + @overload + async def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateDetailedCostReportDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(Only enterprise + customers) or Invoice Id asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 + GenerateDetailedCostReportOperationResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(Only enterprise + customers) or Invoice Id asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either + GenerateDetailedCostReportOperationResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(Only enterprise + customers) or Invoice Id asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 + GenerateDetailedCostReportOperationResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.GenerateDetailedCostReportOperationResult] + 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_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py index 04654269eb88..3417eb3fa503 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,298 +6,315 @@ # 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, Generic, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +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, HttpRequest +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._generate_reservation_details_report_operations import ( + build_by_billing_account_id_request, + build_by_billing_profile_id_request, +) -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GenerateReservationDetailsReportOperations: - """GenerateReservationDetailsReportOperations 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 GenerateReservationDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`generate_reservation_details_report` 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 _by_billing_account_id_initial( - self, - billing_account_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> Optional["_models.OperationStatus"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_account_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_account_id_request( + billing_account_id=billing_account_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_account_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + 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 - _by_billing_account_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_account_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace_async async def begin_by_billing_account_id( - self, - billing_account_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.OperationStatus"]: + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously based on - enrollment id. + enrollment id. The Reservation usage details can be viewed only by certain enterprise roles. + For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. - :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). + :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). Required. :type billing_account_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :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. + :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 OperationStatus or the result of cls(response) + :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 OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + 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._by_billing_account_id_initial( + raw_result = await self._by_billing_account_id_initial( # type: ignore billing_account_id=billing_account_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_account_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_account_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore async def _by_billing_profile_id_initial( - self, - billing_account_id: str, - billing_profile_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> Optional["_models.OperationStatus"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_profile_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_profile_id_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_profile_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + 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 - _by_billing_profile_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_profile_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace_async async def begin_by_billing_profile_id( - self, - billing_account_id: str, - billing_profile_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.OperationStatus"]: + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously by billing - profile. + profile. The Reservation usage details can be viewed by only certain enterprise roles by + default. For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: BillingProfile ID. + :param billing_profile_id: BillingProfile ID. Required. :type billing_profile_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :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. + :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 OperationStatus or the result of cls(response) + :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 OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + 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._by_billing_profile_id_initial( + raw_result = await self._by_billing_profile_id_initial( # type: ignore billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_profile_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_profile_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py index e9b536504b06..67f92f37c731 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,95 @@ # 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, Generic, Optional, TypeVar -import warnings +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, HttpRequest +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._operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available cost management REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +103,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(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]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/operations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.CostManagement/operations"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py index 7a973c90e3c8..9166489e0fb6 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,47 +6,54 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +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._query_operations import build_usage_by_external_cloud_provider_type_request, build_usage_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class QueryOperations: - """QueryOperations 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 QueryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`query` 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") + @overload async def usage( - self, - scope: str, - parameters: "_models.QueryDefinition", - **kwargs: Any - ) -> Optional["_models.QueryResult"]: + self, scope: str, parameters: _models.QueryDefinition, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: """Query the usage data for scope defined. :param scope: The scope associated with query and export operations. This includes @@ -63,127 +71,295 @@ async def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def usage( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) + :return: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def usage( + self, scope: str, parameters: Union[_models.QueryDefinition, IO], **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.QueryResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.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, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/query'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/query"} # type: ignore + + @overload async def usage_by_external_cloud_provider_type( self, external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], external_cloud_provider_id: str, - parameters: "_models.QueryDefinition", + parameters: _models.QueryDefinition, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.QueryResult": + ) -> _models.QueryResult: """Query the usage data for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) + :return: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: Union[_models.QueryDefinition, IO], + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage_by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.QueryResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage_by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage_by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query'} # type: ignore + + usage_by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py deleted file mode 100644 index 2a0f8f9e272e..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py +++ /dev/null @@ -1,273 +0,0 @@ -# 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, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models - -T = TypeVar('T') -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - -class SettingsOperations: - """SettingsOperations 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. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. - """ - - models = _models - - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.SettingsListResult"]: - """Lists all of the settings that have been customized. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SettingsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.SettingsListResult] - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SettingsListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) - return request - - async def extract_data(pipeline_response): - deserialized = self._deserialize('SettingsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/settings'} # type: ignore - - async def get( - self, - setting_name: str, - **kwargs: Any - ) -> "_models.Setting": - """Retrieves the current value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - async def create_or_update( - self, - setting_name: str, - parameters: "_models.Setting", - **kwargs: Any - ) -> "_models.Setting": - """Sets a new value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :param parameters: Body supplied to the CreateOrUpdate setting operation. - :type parameters: ~azure.mgmt.costmanagement.models.Setting - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Setting') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - async def delete( - self, - setting_name: str, - **kwargs: Any - ) -> None: - """Remove the current value for a specific setting and reverts back to the default value, if - applicable. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py index a82f547d6103..4c81759cc0cc 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,105 @@ # 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, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._views_operations import ( + build_create_or_update_by_scope_request, + build_create_or_update_request, + build_delete_by_scope_request, + build_delete_request, + build_get_by_scope_request, + build_get_request, + build_list_by_scope_request, + build_list_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ViewsOperations: - """ViewsOperations 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 ViewsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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.costmanagement.aio.CostManagementClient`'s + :attr:`views` 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") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.ViewListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.View"]: """Lists all views by tenant and object. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,26 +113,24 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/views'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list_by_scope( - self, - scope: str, - **kwargs: Any - ) -> AsyncIterable["_models.ViewListResult"]: + list.metadata = {"url": "/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace + def list_by_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.View"]: """Lists all views at the given scope. :param scope: The scope associated with view operations. This includes @@ -127,46 +149,49 @@ def list_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -175,200 +200,253 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get( - self, - view_name: str, - **kwargs: Any - ) -> "_models.View": + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace_async + async def get(self, view_name: str, **kwargs: Any) -> _models.View: """Gets the view by view name. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + view_name=view_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload async def create_or_update( - self, - view_name: str, - parameters: "_models.View", - **kwargs: Any - ) -> "_models.View": + self, view_name: str, parameters: _models.View, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] 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 = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_request( + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - async def delete( - self, - view_name: str, - **kwargs: Any - ) -> None: + create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace_async + async def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """The operation to delete a view. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + view_name=view_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore - async def get_by_scope( - self, - scope: str, - view_name: str, - **kwargs: Any - ) -> "_models.View": + @distributed_trace_async + async def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.View: """Gets the view for the defined scope by view name. :param scope: The scope associated with view operations. This includes @@ -387,63 +465,70 @@ async def get_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + request = build_get_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.get_by_scope.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 + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload async def create_or_update_by_scope( self, scope: str, view_name: str, - parameters: "_models.View", + parameters: _models.View, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.View": + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -464,72 +549,163 @@ async def create_or_update_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] 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 = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - async def delete_by_scope( - self, - scope: str, - view_name: str, - **kwargs: Any + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace_async + async def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, view_name: str, **kwargs: Any ) -> None: """The operation to delete a view. @@ -549,49 +725,52 @@ async def delete_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.delete_by_scope.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 + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py index c55fa14a8390..1eb1ea95d473 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py @@ -6,245 +6,236 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import Alert - from ._models_py3 import AlertPropertiesDefinition - from ._models_py3 import AlertPropertiesDetails - from ._models_py3 import AlertsResult - from ._models_py3 import CacheItem - from ._models_py3 import CommonExportProperties - from ._models_py3 import Dimension - from ._models_py3 import DimensionsListResult - from ._models_py3 import DismissAlertPayload - from ._models_py3 import ErrorDetails - from ._models_py3 import ErrorResponse - from ._models_py3 import Export - from ._models_py3 import ExportDefinition - from ._models_py3 import ExportDeliveryDestination - from ._models_py3 import ExportDeliveryInfo - from ._models_py3 import ExportExecution - from ._models_py3 import ExportExecutionListResult - from ._models_py3 import ExportListResult - from ._models_py3 import ExportProperties - from ._models_py3 import ExportRecurrencePeriod - from ._models_py3 import ExportSchedule - from ._models_py3 import ForecastDefinition - from ._models_py3 import KpiProperties - from ._models_py3 import Operation - from ._models_py3 import OperationDisplay - from ._models_py3 import OperationListResult - from ._models_py3 import OperationStatus - from ._models_py3 import PivotProperties - from ._models_py3 import ProxyResource - from ._models_py3 import ProxySettingResource - from ._models_py3 import QueryAggregation - from ._models_py3 import QueryColumn - from ._models_py3 import QueryComparisonExpression - from ._models_py3 import QueryDataset - from ._models_py3 import QueryDatasetAutoGenerated - from ._models_py3 import QueryDatasetConfiguration - from ._models_py3 import QueryDefinition - from ._models_py3 import QueryFilter - from ._models_py3 import QueryFilterAutoGenerated - from ._models_py3 import QueryGrouping - from ._models_py3 import QueryResult - from ._models_py3 import QueryTimePeriod - from ._models_py3 import ReportConfigAggregation - from ._models_py3 import ReportConfigComparisonExpression - from ._models_py3 import ReportConfigDataset - from ._models_py3 import ReportConfigDatasetConfiguration - from ._models_py3 import ReportConfigFilter - from ._models_py3 import ReportConfigGrouping - from ._models_py3 import ReportConfigSorting - from ._models_py3 import ReportConfigTimePeriod - from ._models_py3 import Resource - from ._models_py3 import Setting - from ._models_py3 import SettingsListResult - from ._models_py3 import Status - from ._models_py3 import View - from ._models_py3 import ViewListResult -except (SyntaxError, ImportError): - from ._models import Alert # type: ignore - from ._models import AlertPropertiesDefinition # type: ignore - from ._models import AlertPropertiesDetails # type: ignore - from ._models import AlertsResult # type: ignore - from ._models import CacheItem # type: ignore - from ._models import CommonExportProperties # type: ignore - from ._models import Dimension # type: ignore - from ._models import DimensionsListResult # type: ignore - from ._models import DismissAlertPayload # type: ignore - from ._models import ErrorDetails # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import Export # type: ignore - from ._models import ExportDefinition # type: ignore - from ._models import ExportDeliveryDestination # type: ignore - from ._models import ExportDeliveryInfo # type: ignore - from ._models import ExportExecution # type: ignore - from ._models import ExportExecutionListResult # type: ignore - from ._models import ExportListResult # type: ignore - from ._models import ExportProperties # type: ignore - from ._models import ExportRecurrencePeriod # type: ignore - from ._models import ExportSchedule # type: ignore - from ._models import ForecastDefinition # type: ignore - from ._models import KpiProperties # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplay # type: ignore - from ._models import OperationListResult # type: ignore - from ._models import OperationStatus # type: ignore - from ._models import PivotProperties # type: ignore - from ._models import ProxyResource # type: ignore - from ._models import ProxySettingResource # type: ignore - from ._models import QueryAggregation # type: ignore - from ._models import QueryColumn # type: ignore - from ._models import QueryComparisonExpression # type: ignore - from ._models import QueryDataset # type: ignore - from ._models import QueryDatasetAutoGenerated # type: ignore - from ._models import QueryDatasetConfiguration # type: ignore - from ._models import QueryDefinition # type: ignore - from ._models import QueryFilter # type: ignore - from ._models import QueryFilterAutoGenerated # type: ignore - from ._models import QueryGrouping # type: ignore - from ._models import QueryResult # type: ignore - from ._models import QueryTimePeriod # type: ignore - from ._models import ReportConfigAggregation # type: ignore - from ._models import ReportConfigComparisonExpression # type: ignore - from ._models import ReportConfigDataset # type: ignore - from ._models import ReportConfigDatasetConfiguration # type: ignore - from ._models import ReportConfigFilter # type: ignore - from ._models import ReportConfigGrouping # type: ignore - from ._models import ReportConfigSorting # type: ignore - from ._models import ReportConfigTimePeriod # type: ignore - from ._models import Resource # type: ignore - from ._models import Setting # type: ignore - from ._models import SettingsListResult # type: ignore - from ._models import Status # type: ignore - from ._models import View # type: ignore - from ._models import ViewListResult # type: ignore +from ._models_py3 import Alert +from ._models_py3 import AlertPropertiesDefinition +from ._models_py3 import AlertPropertiesDetails +from ._models_py3 import AlertsResult +from ._models_py3 import BlobInfo +from ._models_py3 import CommonExportProperties +from ._models_py3 import CostDetailsOperationResults +from ._models_py3 import CostDetailsTimePeriod +from ._models_py3 import Dimension +from ._models_py3 import DimensionsListResult +from ._models_py3 import DismissAlertPayload +from ._models_py3 import ErrorDetails +from ._models_py3 import ErrorResponse +from ._models_py3 import Export +from ._models_py3 import ExportDataset +from ._models_py3 import ExportDatasetConfiguration +from ._models_py3 import ExportDefinition +from ._models_py3 import ExportDeliveryDestination +from ._models_py3 import ExportDeliveryInfo +from ._models_py3 import ExportExecution +from ._models_py3 import ExportExecutionListResult +from ._models_py3 import ExportListResult +from ._models_py3 import ExportProperties +from ._models_py3 import ExportRecurrencePeriod +from ._models_py3 import ExportSchedule +from ._models_py3 import ExportTimePeriod +from ._models_py3 import ForecastAggregation +from ._models_py3 import ForecastColumn +from ._models_py3 import ForecastComparisonExpression +from ._models_py3 import ForecastDataset +from ._models_py3 import ForecastDatasetConfiguration +from ._models_py3 import ForecastDefinition +from ._models_py3 import ForecastFilter +from ._models_py3 import ForecastResult +from ._models_py3 import ForecastTimePeriod +from ._models_py3 import GenerateCostDetailsReportErrorResponse +from ._models_py3 import GenerateCostDetailsReportRequestDefinition +from ._models_py3 import GenerateDetailedCostReportDefinition +from ._models_py3 import GenerateDetailedCostReportErrorResponse +from ._models_py3 import GenerateDetailedCostReportOperationResult +from ._models_py3 import GenerateDetailedCostReportOperationStatuses +from ._models_py3 import GenerateDetailedCostReportTimePeriod +from ._models_py3 import KpiProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import OperationStatus +from ._models_py3 import PivotProperties +from ._models_py3 import ProxyResource +from ._models_py3 import QueryAggregation +from ._models_py3 import QueryColumn +from ._models_py3 import QueryComparisonExpression +from ._models_py3 import QueryDataset +from ._models_py3 import QueryDatasetConfiguration +from ._models_py3 import QueryDefinition +from ._models_py3 import QueryFilter +from ._models_py3 import QueryGrouping +from ._models_py3 import QueryResult +from ._models_py3 import QueryTimePeriod +from ._models_py3 import ReportConfigAggregation +from ._models_py3 import ReportConfigComparisonExpression +from ._models_py3 import ReportConfigDataset +from ._models_py3 import ReportConfigDatasetConfiguration +from ._models_py3 import ReportConfigFilter +from ._models_py3 import ReportConfigGrouping +from ._models_py3 import ReportConfigSorting +from ._models_py3 import ReportConfigTimePeriod +from ._models_py3 import Resource +from ._models_py3 import Status +from ._models_py3 import View +from ._models_py3 import ViewListResult -from ._cost_management_client_enums import ( - AccumulatedType, - AlertCategory, - AlertCriteria, - AlertOperator, - AlertSource, - AlertStatus, - AlertTimeGrainType, - AlertType, - ChartType, - ExecutionStatus, - ExecutionType, - ExportType, - ExternalCloudProviderType, - ForecastTimeframeType, - ForecastType, - FormatType, - FunctionType, - GranularityType, - KpiType, - MetricType, - OperationStatusType, - OperatorType, - PivotType, - QueryColumnType, - RecurrenceType, - ReportConfigColumnType, - ReportConfigSortingDirection, - ReportGranularityType, - ReportTimeframeType, - ReportType, - SettingsPropertiesStartOn, - StatusType, - TimeframeType, -) +from ._cost_management_client_enums import AccumulatedType +from ._cost_management_client_enums import AlertCategory +from ._cost_management_client_enums import AlertCriteria +from ._cost_management_client_enums import AlertOperator +from ._cost_management_client_enums import AlertSource +from ._cost_management_client_enums import AlertStatus +from ._cost_management_client_enums import AlertTimeGrainType +from ._cost_management_client_enums import AlertType +from ._cost_management_client_enums import ChartType +from ._cost_management_client_enums import CostDetailsDataFormat +from ._cost_management_client_enums import CostDetailsMetricType +from ._cost_management_client_enums import CostDetailsStatusType +from ._cost_management_client_enums import ExecutionStatus +from ._cost_management_client_enums import ExecutionType +from ._cost_management_client_enums import ExportType +from ._cost_management_client_enums import ExternalCloudProviderType +from ._cost_management_client_enums import ForecastOperatorType +from ._cost_management_client_enums import ForecastTimeframe +from ._cost_management_client_enums import ForecastType +from ._cost_management_client_enums import FormatType +from ._cost_management_client_enums import FunctionName +from ._cost_management_client_enums import FunctionType +from ._cost_management_client_enums import GenerateDetailedCostReportMetricType +from ._cost_management_client_enums import GranularityType +from ._cost_management_client_enums import KpiType +from ._cost_management_client_enums import MetricType +from ._cost_management_client_enums import OperationStatusType +from ._cost_management_client_enums import OperatorType +from ._cost_management_client_enums import PivotType +from ._cost_management_client_enums import QueryColumnType +from ._cost_management_client_enums import QueryOperatorType +from ._cost_management_client_enums import RecurrenceType +from ._cost_management_client_enums import ReportConfigColumnType +from ._cost_management_client_enums import ReportConfigSortingType +from ._cost_management_client_enums import ReportGranularityType +from ._cost_management_client_enums import ReportOperationStatusType +from ._cost_management_client_enums import ReportTimeframeType +from ._cost_management_client_enums import ReportType +from ._cost_management_client_enums import ReservationReportSchema +from ._cost_management_client_enums import StatusType +from ._cost_management_client_enums import TimeframeType +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__ = [ - 'Alert', - 'AlertPropertiesDefinition', - 'AlertPropertiesDetails', - 'AlertsResult', - 'CacheItem', - 'CommonExportProperties', - 'Dimension', - 'DimensionsListResult', - 'DismissAlertPayload', - 'ErrorDetails', - 'ErrorResponse', - 'Export', - 'ExportDefinition', - 'ExportDeliveryDestination', - 'ExportDeliveryInfo', - 'ExportExecution', - 'ExportExecutionListResult', - 'ExportListResult', - 'ExportProperties', - 'ExportRecurrencePeriod', - 'ExportSchedule', - 'ForecastDefinition', - 'KpiProperties', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'OperationStatus', - 'PivotProperties', - 'ProxyResource', - 'ProxySettingResource', - 'QueryAggregation', - 'QueryColumn', - 'QueryComparisonExpression', - 'QueryDataset', - 'QueryDatasetAutoGenerated', - 'QueryDatasetConfiguration', - 'QueryDefinition', - 'QueryFilter', - 'QueryFilterAutoGenerated', - 'QueryGrouping', - 'QueryResult', - 'QueryTimePeriod', - 'ReportConfigAggregation', - 'ReportConfigComparisonExpression', - 'ReportConfigDataset', - 'ReportConfigDatasetConfiguration', - 'ReportConfigFilter', - 'ReportConfigGrouping', - 'ReportConfigSorting', - 'ReportConfigTimePeriod', - 'Resource', - 'Setting', - 'SettingsListResult', - 'Status', - 'View', - 'ViewListResult', - 'AccumulatedType', - 'AlertCategory', - 'AlertCriteria', - 'AlertOperator', - 'AlertSource', - 'AlertStatus', - 'AlertTimeGrainType', - 'AlertType', - 'ChartType', - 'ExecutionStatus', - 'ExecutionType', - 'ExportType', - 'ExternalCloudProviderType', - 'ForecastTimeframeType', - 'ForecastType', - 'FormatType', - 'FunctionType', - 'GranularityType', - 'KpiType', - 'MetricType', - 'OperationStatusType', - 'OperatorType', - 'PivotType', - 'QueryColumnType', - 'RecurrenceType', - 'ReportConfigColumnType', - 'ReportConfigSortingDirection', - 'ReportGranularityType', - 'ReportTimeframeType', - 'ReportType', - 'SettingsPropertiesStartOn', - 'StatusType', - 'TimeframeType', + "Alert", + "AlertPropertiesDefinition", + "AlertPropertiesDetails", + "AlertsResult", + "BlobInfo", + "CommonExportProperties", + "CostDetailsOperationResults", + "CostDetailsTimePeriod", + "Dimension", + "DimensionsListResult", + "DismissAlertPayload", + "ErrorDetails", + "ErrorResponse", + "Export", + "ExportDataset", + "ExportDatasetConfiguration", + "ExportDefinition", + "ExportDeliveryDestination", + "ExportDeliveryInfo", + "ExportExecution", + "ExportExecutionListResult", + "ExportListResult", + "ExportProperties", + "ExportRecurrencePeriod", + "ExportSchedule", + "ExportTimePeriod", + "ForecastAggregation", + "ForecastColumn", + "ForecastComparisonExpression", + "ForecastDataset", + "ForecastDatasetConfiguration", + "ForecastDefinition", + "ForecastFilter", + "ForecastResult", + "ForecastTimePeriod", + "GenerateCostDetailsReportErrorResponse", + "GenerateCostDetailsReportRequestDefinition", + "GenerateDetailedCostReportDefinition", + "GenerateDetailedCostReportErrorResponse", + "GenerateDetailedCostReportOperationResult", + "GenerateDetailedCostReportOperationStatuses", + "GenerateDetailedCostReportTimePeriod", + "KpiProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "OperationStatus", + "PivotProperties", + "ProxyResource", + "QueryAggregation", + "QueryColumn", + "QueryComparisonExpression", + "QueryDataset", + "QueryDatasetConfiguration", + "QueryDefinition", + "QueryFilter", + "QueryGrouping", + "QueryResult", + "QueryTimePeriod", + "ReportConfigAggregation", + "ReportConfigComparisonExpression", + "ReportConfigDataset", + "ReportConfigDatasetConfiguration", + "ReportConfigFilter", + "ReportConfigGrouping", + "ReportConfigSorting", + "ReportConfigTimePeriod", + "Resource", + "Status", + "View", + "ViewListResult", + "AccumulatedType", + "AlertCategory", + "AlertCriteria", + "AlertOperator", + "AlertSource", + "AlertStatus", + "AlertTimeGrainType", + "AlertType", + "ChartType", + "CostDetailsDataFormat", + "CostDetailsMetricType", + "CostDetailsStatusType", + "ExecutionStatus", + "ExecutionType", + "ExportType", + "ExternalCloudProviderType", + "ForecastOperatorType", + "ForecastTimeframe", + "ForecastType", + "FormatType", + "FunctionName", + "FunctionType", + "GenerateDetailedCostReportMetricType", + "GranularityType", + "KpiType", + "MetricType", + "OperationStatusType", + "OperatorType", + "PivotType", + "QueryColumnType", + "QueryOperatorType", + "RecurrenceType", + "ReportConfigColumnType", + "ReportConfigSortingType", + "ReportGranularityType", + "ReportOperationStatusType", + "ReportTimeframeType", + "ReportType", + "ReservationReportSchema", + "StatusType", + "TimeframeType", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py index eac0fd7748ff..2c605f46977c 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py @@ -6,45 +6,28 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class AccumulatedType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Show costs accumulated over time. - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccumulatedType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Show costs accumulated over time.""" TRUE = "true" FALSE = "false" -class AlertCategory(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Alert category - """ + +class AlertCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Alert category.""" COST = "Cost" USAGE = "Usage" BILLING = "Billing" SYSTEM = "System" -class AlertCriteria(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Criteria that triggered alert - """ + +class AlertCriteria(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Criteria that triggered alert.""" COST_THRESHOLD_EXCEEDED = "CostThresholdExceeded" USAGE_THRESHOLD_EXCEEDED = "UsageThresholdExceeded" @@ -61,9 +44,9 @@ class AlertCriteria(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): CROSS_CLOUD_COLLECTION_ERROR = "CrossCloudCollectionError" GENERAL_THRESHOLD_ERROR = "GeneralThresholdError" -class AlertOperator(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """operator used to compare currentSpend with amount - """ + +class AlertOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """operator used to compare currentSpend with amount.""" NONE = "None" EQUAL_TO = "EqualTo" @@ -72,16 +55,16 @@ class AlertOperator(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): LESS_THAN = "LessThan" LESS_THAN_OR_EQUAL_TO = "LessThanOrEqualTo" -class AlertSource(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Source of alert - """ + +class AlertSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Source of alert.""" PRESET = "Preset" USER = "User" -class AlertStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """alert status - """ + +class AlertStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """alert status.""" NONE = "None" ACTIVE = "Active" @@ -89,9 +72,9 @@ class AlertStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): RESOLVED = "Resolved" DISMISSED = "Dismissed" -class AlertTimeGrainType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Type of timegrain cadence - """ + +class AlertTimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of timegrain cadence.""" NONE = "None" MONTHLY = "Monthly" @@ -101,9 +84,9 @@ class AlertTimeGrainType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): BILLING_QUARTER = "BillingQuarter" BILLING_ANNUAL = "BillingAnnual" -class AlertType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """type of alert - """ + +class AlertType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """type of alert.""" BUDGET = "Budget" INVOICE = "Invoice" @@ -113,9 +96,9 @@ class AlertType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): X_CLOUD = "xCloud" BUDGET_FORECAST = "BudgetForecast" -class ChartType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Chart type of the main view in Cost Analysis. Required. - """ + +class ChartType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Chart type of the main view in Cost Analysis. Required.""" AREA = "Area" LINE = "Line" @@ -123,9 +106,36 @@ class ChartType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): GROUPED_COLUMN = "GroupedColumn" TABLE = "Table" -class ExecutionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the export execution. - """ + +class CostDetailsDataFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The data format of the report.""" + + #: Csv data format. + CSV_COST_DETAILS_DATA_FORMAT = "Csv" + + +class CostDetailsMetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the detailed report. By default ActualCost is provided.""" + + #: Actual cost data. + ACTUAL_COST_COST_DETAILS_METRIC_TYPE = "ActualCost" + #: Amortized cost data. + AMORTIZED_COST_COST_DETAILS_METRIC_TYPE = "AmortizedCost" + + +class CostDetailsStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the cost details operation.""" + + #: Operation is Completed. + COMPLETED_COST_DETAILS_STATUS_TYPE = "Completed" + #: Operation is Completed and no cost data found. + NO_DATA_FOUND_COST_DETAILS_STATUS_TYPE = "NoDataFound" + #: Operation Failed. + FAILED_COST_DETAILS_STATUS_TYPE = "Failed" + + +class ExecutionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The last known status of the export execution.""" QUEUED = "Queued" IN_PROGRESS = "InProgress" @@ -135,142 +145,176 @@ class ExecutionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): NEW_DATA_NOT_AVAILABLE = "NewDataNotAvailable" DATA_NOT_AVAILABLE = "DataNotAvailable" -class ExecutionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the export execution. - """ + +class ExecutionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the export execution.""" ON_DEMAND = "OnDemand" SCHEDULED = "Scheduled" -class ExportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the query. - """ + +class ExportType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the query.""" USAGE = "Usage" ACTUAL_COST = "ActualCost" AMORTIZED_COST = "AmortizedCost" -class ExternalCloudProviderType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ExternalCloudProviderType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ExternalCloudProviderType.""" EXTERNAL_SUBSCRIPTIONS = "externalSubscriptions" EXTERNAL_BILLING_ACCOUNTS = "externalBillingAccounts" -class ForecastTimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The time frame for pulling data for the forecast. If custom, then a specific time period must - be provided. - """ - MONTH_TO_DATE = "MonthToDate" - BILLING_MONTH_TO_DATE = "BillingMonthToDate" - THE_LAST_MONTH = "TheLastMonth" - THE_LAST_BILLING_MONTH = "TheLastBillingMonth" - WEEK_TO_DATE = "WeekToDate" +class ForecastOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operator to use for comparison.""" + + IN = "In" + + +class ForecastTimeframe(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The time frame for pulling data for the forecast.""" + CUSTOM = "Custom" -class ForecastType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the forecast. - """ + +class ForecastType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the forecast.""" USAGE = "Usage" ACTUAL_COST = "ActualCost" AMORTIZED_COST = "AmortizedCost" -class FormatType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The format of the export being delivered. - """ + +class FormatType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The format of the export being delivered. Currently only 'Csv' is supported.""" CSV = "Csv" -class FunctionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The name of the aggregation function to use. - """ - AVG = "Avg" - MAX = "Max" - MIN = "Min" +class FunctionName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The name of the column to aggregate.""" + + PRE_TAX_COST_USD = "PreTaxCostUSD" + COST = "Cost" + COST_USD = "CostUSD" + PRE_TAX_COST = "PreTaxCost" + + +class FunctionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The name of the aggregation function to use.""" + SUM = "Sum" -class GranularityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The granularity of rows in the query. - """ + +class GenerateDetailedCostReportMetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the detailed report. By default ActualCost is provided.""" + + ACTUAL_COST = "ActualCost" + AMORTIZED_COST = "AmortizedCost" + + +class GranularityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The granularity of rows in the forecast.""" DAILY = "Daily" -class KpiType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """KPI type (Forecast, Budget). - """ + +class KpiType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """KPI type (Forecast, Budget).""" FORECAST = "Forecast" BUDGET = "Budget" -class MetricType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Metric to use when displaying costs. - """ + +class MetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Metric to use when displaying costs.""" ACTUAL_COST = "ActualCost" AMORTIZED_COST = "AmortizedCost" AHUB = "AHUB" -class OperationStatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the long running operation. - """ + +class OperationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the long running operation.""" RUNNING = "Running" COMPLETED = "Completed" FAILED = "Failed" -class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The operator to use for comparison. - """ - IN_ENUM = "In" +class OperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operator to use for comparison.""" + + IN = "In" CONTAINS = "Contains" -class PivotType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Data type to show in view. - """ + +class PivotType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Data type to show in view.""" DIMENSION = "Dimension" TAG_KEY = "TagKey" -class QueryColumnType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the column in the export. - """ + +class QueryColumnType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the column in the export.""" TAG = "Tag" DIMENSION = "Dimension" -class RecurrenceType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The schedule recurrence. - """ + +class QueryOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operator to use for comparison.""" + + IN = "In" + + +class RecurrenceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The schedule recurrence.""" DAILY = "Daily" WEEKLY = "Weekly" MONTHLY = "Monthly" ANNUALLY = "Annually" -class ReportConfigColumnType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the column in the report. - """ + +class ReportConfigColumnType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the column in the report.""" TAG = "Tag" DIMENSION = "Dimension" -class ReportConfigSortingDirection(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Direction of sort. - """ + +class ReportConfigSortingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Direction of sort.""" ASCENDING = "Ascending" DESCENDING = "Descending" -class ReportGranularityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The granularity of rows in the report. - """ + +class ReportGranularityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The granularity of rows in the report.""" DAILY = "Daily" MONTHLY = "Monthly" -class ReportTimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ReportOperationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the long running operation.""" + + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + FAILED = "Failed" + QUEUED = "Queued" + NO_DATA_FOUND = "NoDataFound" + READY_TO_DOWNLOAD = "ReadyToDownload" + TIMED_OUT = "TimedOut" + + +class ReportTimeframeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The time frame for pulling data for the report. If custom, then a specific time period must be provided. """ @@ -280,7 +324,8 @@ class ReportTimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): YEAR_TO_DATE = "YearToDate" CUSTOM = "Custom" -class ReportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ReportType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of the report. Usage represents actual usage, forecast represents forecasted data and UsageAndForecast represents both usage and forecasted data. Actual usage and forecasted data can be differentiated based on dates. @@ -288,24 +333,33 @@ class ReportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): USAGE = "Usage" -class SettingsPropertiesStartOn(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Indicates what scope Cost Management in the Azure portal should default to. Allowed values: - LastUsed. + +class ReservationReportSchema(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The CSV file from the reportUrl blob link consists of reservation usage data with the following + schema at daily granularity. """ - LAST_USED = "LastUsed" - SCOPE_PICKER = "ScopePicker" - SPECIFIC_SCOPE = "SpecificScope" + INSTANCE_FLEXIBILITY_GROUP = "InstanceFlexibilityGroup" + INSTANCE_FLEXIBILITY_RATIO = "InstanceFlexibilityRatio" + INSTANCE_ID = "InstanceId" + KIND = "Kind" + RESERVATION_ID = "ReservationId" + RESERVATION_ORDER_ID = "ReservationOrderId" + RESERVED_HOURS = "ReservedHours" + SKU_NAME = "SkuName" + TOTAL_RESERVED_QUANTITY = "TotalReservedQuantity" + USAGE_DATE = "UsageDate" + USED_HOURS = "UsedHours" -class StatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the schedule. Whether active or not. If inactive, the export's scheduled - execution is paused. - """ + +class StatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the export's schedule. If 'Inactive', the export's schedule is paused.""" ACTIVE = "Active" INACTIVE = "Inactive" -class TimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class TimeframeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The time frame for pulling data for the query. If custom, then a specific time period must be provided. """ diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models.py deleted file mode 100644 index ffd3292fd2df..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models.py +++ /dev/null @@ -1,2225 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class Resource(msrest.serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.tags = None - - -class Alert(Resource): - """An individual alert. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Alert, self).__init__(**kwargs) - self.definition = kwargs.get('definition', None) - self.description = kwargs.get('description', None) - self.source = kwargs.get('source', None) - self.details = kwargs.get('details', None) - self.cost_entity_id = kwargs.get('cost_entity_id', None) - self.status = kwargs.get('status', None) - self.creation_time = kwargs.get('creation_time', None) - self.close_time = kwargs.get('close_time', None) - self.modification_time = kwargs.get('modification_time', None) - self.status_modification_user_name = kwargs.get('status_modification_user_name', None) - self.status_modification_time = kwargs.get('status_modification_time', None) - - -class AlertPropertiesDefinition(msrest.serialization.Model): - """defines the type of alert. - - :param type: type of alert. Possible values include: "Budget", "Invoice", "Credit", "Quota", - "General", "xCloud", "BudgetForecast". - :type type: str or ~azure.mgmt.costmanagement.models.AlertType - :param category: Alert category. Possible values include: "Cost", "Usage", "Billing", "System". - :type category: str or ~azure.mgmt.costmanagement.models.AlertCategory - :param criteria: Criteria that triggered alert. Possible values include: - "CostThresholdExceeded", "UsageThresholdExceeded", "CreditThresholdApproaching", - "CreditThresholdReached", "QuotaThresholdApproaching", "QuotaThresholdReached", - "MultiCurrency", "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", - "InvoiceDueDateApproaching", "InvoiceDueDateReached", "CrossCloudNewDataAvailable", - "CrossCloudCollectionError", "GeneralThresholdError". - :type criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'criteria': {'key': 'criteria', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AlertPropertiesDefinition, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.category = kwargs.get('category', None) - self.criteria = kwargs.get('criteria', None) - - -class AlertPropertiesDetails(msrest.serialization.Model): - """Alert details. - - :param time_grain_type: Type of timegrain cadence. Possible values include: "None", "Monthly", - "Quarterly", "Annually", "BillingMonth", "BillingQuarter", "BillingAnnual". - :type time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType - :param period_start_date: datetime of periodStartDate. - :type period_start_date: str - :param triggered_by: notificationId that triggered this alert. - :type triggered_by: str - :param resource_group_filter: array of resourceGroups to filter by. - :type resource_group_filter: list[any] - :param resource_filter: array of resources to filter by. - :type resource_filter: list[any] - :param meter_filter: array of meters to filter by. - :type meter_filter: list[any] - :param tag_filter: tags to filter by. - :type tag_filter: any - :param threshold: notification threshold percentage as a decimal which activated this alert. - :type threshold: float - :param operator: operator used to compare currentSpend with amount. Possible values include: - "None", "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", "LessThanOrEqualTo". - :type operator: str or ~azure.mgmt.costmanagement.models.AlertOperator - :param amount: budget threshold amount. - :type amount: float - :param unit: unit of currency being used. - :type unit: str - :param current_spend: current spend. - :type current_spend: float - :param contact_emails: list of emails to contact. - :type contact_emails: list[str] - :param contact_groups: list of action groups to broadcast to. - :type contact_groups: list[str] - :param contact_roles: list of contact roles. - :type contact_roles: list[str] - :param overriding_alert: overriding alert. - :type overriding_alert: str - """ - - _attribute_map = { - 'time_grain_type': {'key': 'timeGrainType', 'type': 'str'}, - 'period_start_date': {'key': 'periodStartDate', 'type': 'str'}, - 'triggered_by': {'key': 'triggeredBy', 'type': 'str'}, - 'resource_group_filter': {'key': 'resourceGroupFilter', 'type': '[object]'}, - 'resource_filter': {'key': 'resourceFilter', 'type': '[object]'}, - 'meter_filter': {'key': 'meterFilter', 'type': '[object]'}, - 'tag_filter': {'key': 'tagFilter', 'type': 'object'}, - 'threshold': {'key': 'threshold', 'type': 'float'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'current_spend': {'key': 'currentSpend', 'type': 'float'}, - 'contact_emails': {'key': 'contactEmails', 'type': '[str]'}, - 'contact_groups': {'key': 'contactGroups', 'type': '[str]'}, - 'contact_roles': {'key': 'contactRoles', 'type': '[str]'}, - 'overriding_alert': {'key': 'overridingAlert', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AlertPropertiesDetails, self).__init__(**kwargs) - self.time_grain_type = kwargs.get('time_grain_type', None) - self.period_start_date = kwargs.get('period_start_date', None) - self.triggered_by = kwargs.get('triggered_by', None) - self.resource_group_filter = kwargs.get('resource_group_filter', None) - self.resource_filter = kwargs.get('resource_filter', None) - self.meter_filter = kwargs.get('meter_filter', None) - self.tag_filter = kwargs.get('tag_filter', None) - self.threshold = kwargs.get('threshold', None) - self.operator = kwargs.get('operator', None) - self.amount = kwargs.get('amount', None) - self.unit = kwargs.get('unit', None) - self.current_spend = kwargs.get('current_spend', None) - self.contact_emails = kwargs.get('contact_emails', None) - self.contact_groups = kwargs.get('contact_groups', None) - self.contact_roles = kwargs.get('contact_roles', None) - self.overriding_alert = kwargs.get('overriding_alert', None) - - -class AlertsResult(msrest.serialization.Model): - """Result of alerts. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of alerts. - :vartype value: list[~azure.mgmt.costmanagement.models.Alert] - :ivar next_link: URL to get the next set of alerts results if there are any. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Alert]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AlertsResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class CacheItem(msrest.serialization.Model): - """CacheItem. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Resource ID used by Resource Manager to uniquely identify the scope. - :type id: str - :param name: Required. Display name for the scope. - :type name: str - :param channel: Required. Indicates the account type. Allowed values include: EA, PAYG, Modern, - Internal, Unknown. - :type channel: str - :param subchannel: Required. Indicates the type of modern account. Allowed values include: - Individual, Enterprise, Partner, Indirect, NotApplicable. - :type subchannel: str - :param parent: Resource ID of the parent scope. For instance, subscription's resource ID for a - resource group or a management group resource ID for a subscription. - :type parent: str - :param status: Indicates the status of the scope. Status only applies to subscriptions and - billing accounts. - :type status: str - """ - - _validation = { - 'id': {'required': True}, - 'name': {'required': True}, - 'channel': {'required': True}, - 'subchannel': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'channel': {'key': 'channel', 'type': 'str'}, - 'subchannel': {'key': 'subchannel', 'type': 'str'}, - 'parent': {'key': 'parent', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CacheItem, self).__init__(**kwargs) - self.id = kwargs['id'] - self.name = kwargs['name'] - self.channel = kwargs['channel'] - self.subchannel = kwargs['subchannel'] - self.parent = kwargs.get('parent', None) - self.status = kwargs.get('status', None) - - -class CommonExportProperties(msrest.serialization.Model): - """The common properties of the export. - - All required parameters must be populated in order to send to Azure. - - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - """ - - _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, - } - - _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, - } - - def __init__( - self, - **kwargs - ): - super(CommonExportProperties, self).__init__(**kwargs) - self.format = kwargs.get('format', None) - self.delivery_info = kwargs['delivery_info'] - self.definition = kwargs['definition'] - - -class Dimension(Resource): - """Dimension. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :ivar description: Dimension description. - :vartype description: str - :ivar filter_enabled: Filter enabled. - :vartype filter_enabled: bool - :ivar grouping_enabled: Grouping enabled. - :vartype grouping_enabled: bool - :param data: - :type data: list[str] - :ivar total: Total number of data for the dimension. - :vartype total: int - :ivar category: Dimension category. - :vartype category: str - :ivar usage_start: Usage start. - :vartype usage_start: ~datetime.datetime - :ivar usage_end: Usage end. - :vartype usage_end: ~datetime.datetime - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'description': {'readonly': True}, - 'filter_enabled': {'readonly': True}, - 'grouping_enabled': {'readonly': True}, - 'total': {'readonly': True}, - 'category': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'filter_enabled': {'key': 'properties.filterEnabled', 'type': 'bool'}, - 'grouping_enabled': {'key': 'properties.groupingEnabled', 'type': 'bool'}, - 'data': {'key': 'properties.data', 'type': '[str]'}, - 'total': {'key': 'properties.total', 'type': 'int'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'iso-8601'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'iso-8601'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Dimension, self).__init__(**kwargs) - self.description = None - self.filter_enabled = None - self.grouping_enabled = None - self.data = kwargs.get('data', None) - self.total = None - self.category = None - self.usage_start = None - self.usage_end = None - self.next_link = None - - -class DimensionsListResult(msrest.serialization.Model): - """Result of listing dimensions. It contains a list of available dimensions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of dimensions. - :vartype value: list[~azure.mgmt.costmanagement.models.Dimension] - """ - - _validation = { - 'value': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Dimension]'}, - } - - def __init__( - self, - **kwargs - ): - super(DimensionsListResult, self).__init__(**kwargs) - self.value = None - - -class DismissAlertPayload(msrest.serialization.Model): - """The request payload to update an alert. - - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str - """ - - _attribute_map = { - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DismissAlertPayload, self).__init__(**kwargs) - self.definition = kwargs.get('definition', None) - self.description = kwargs.get('description', None) - self.source = kwargs.get('source', None) - self.details = kwargs.get('details', None) - self.cost_entity_id = kwargs.get('cost_entity_id', None) - self.status = kwargs.get('status', None) - self.creation_time = kwargs.get('creation_time', None) - self.close_time = kwargs.get('close_time', None) - self.modification_time = kwargs.get('modification_time', None) - self.status_modification_user_name = kwargs.get('status_modification_user_name', None) - self.status_modification_time = kwargs.get('status_modification_time', None) - - -class ErrorDetails(msrest.serialization.Model): - """The details of the error. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetails, self).__init__(**kwargs) - self.code = None - self.message = None - - -class ErrorResponse(msrest.serialization.Model): - """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. - -Some Error responses: - - -* - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. - -* - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. - - :param error: The details of the error. - :type error: ~azure.mgmt.costmanagement.models.ErrorDetails - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ProxyResource(msrest.serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ProxyResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.e_tag = kwargs.get('e_tag', None) - - -class Export(ProxyResource): - """A export resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'format': {'key': 'properties.format', 'type': 'str'}, - 'delivery_info': {'key': 'properties.deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'properties.definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'properties.schedule', 'type': 'ExportSchedule'}, - } - - def __init__( - self, - **kwargs - ): - super(Export, self).__init__(**kwargs) - self.format = kwargs.get('format', None) - self.delivery_info = kwargs.get('delivery_info', None) - self.definition = kwargs.get('definition', None) - self.schedule = kwargs.get('schedule', None) - - -class ExportDefinition(msrest.serialization.Model): - """The definition of a query. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", - "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param data_set: Has definition for data in this query. - :type data_set: ~azure.mgmt.costmanagement.models.QueryDatasetAutoGenerated - """ - - _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'data_set': {'key': 'dataSet', 'type': 'QueryDatasetAutoGenerated'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportDefinition, self).__init__(**kwargs) - self.type = kwargs['type'] - self.timeframe = kwargs['timeframe'] - self.time_period = kwargs.get('time_period', None) - self.data_set = kwargs.get('data_set', None) - - -class ExportDeliveryDestination(msrest.serialization.Model): - """The destination information for the delivery of the export. To allow access to a storage account, you must register the account's subscription with the Microsoft.CostManagementExports resource provider. This is required once per subscription. When creating an export in the Azure portal, it is done automatically, however API users need to register the subscription. For more information see https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services . - - All required parameters must be populated in order to send to Azure. - - :param resource_id: Required. The resource id of the storage account where exports will be - delivered. - :type resource_id: str - :param container: Required. The name of the container where exports will be uploaded. - :type container: str - :param root_folder_path: The name of the directory where exports will be uploaded. - :type root_folder_path: str - """ - - _validation = { - 'resource_id': {'required': True}, - 'container': {'required': True}, - } - - _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'container': {'key': 'container', 'type': 'str'}, - 'root_folder_path': {'key': 'rootFolderPath', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportDeliveryDestination, self).__init__(**kwargs) - self.resource_id = kwargs['resource_id'] - self.container = kwargs['container'] - self.root_folder_path = kwargs.get('root_folder_path', None) - - -class ExportDeliveryInfo(msrest.serialization.Model): - """The delivery information associated with a export. - - All required parameters must be populated in order to send to Azure. - - :param destination: Required. Has destination for the export being delivered. - :type destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination - """ - - _validation = { - 'destination': {'required': True}, - } - - _attribute_map = { - 'destination': {'key': 'destination', 'type': 'ExportDeliveryDestination'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportDeliveryInfo, self).__init__(**kwargs) - self.destination = kwargs['destination'] - - -class ExportExecution(Resource): - """A export execution. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param execution_type: The type of the export execution. Possible values include: "OnDemand", - "Scheduled". - :type execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType - :param status: The status of the export execution. Possible values include: "Queued", - "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", "DataNotAvailable". - :type status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus - :param submitted_by: The identifier for the entity that executed the export. For OnDemand - executions, it is the email id. For Scheduled executions, it is the constant value - System. - :type submitted_by: str - :param submitted_time: The time when export was queued to be executed. - :type submitted_time: ~datetime.datetime - :param processing_start_time: The time when export was picked up to be executed. - :type processing_start_time: ~datetime.datetime - :param processing_end_time: The time when export execution finished. - :type processing_end_time: ~datetime.datetime - :param file_name: The name of the file export got written to. - :type file_name: str - :param run_settings: The common properties of the export. - :type run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'execution_type': {'key': 'properties.executionType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'submitted_by': {'key': 'properties.submittedBy', 'type': 'str'}, - 'submitted_time': {'key': 'properties.submittedTime', 'type': 'iso-8601'}, - 'processing_start_time': {'key': 'properties.processingStartTime', 'type': 'iso-8601'}, - 'processing_end_time': {'key': 'properties.processingEndTime', 'type': 'iso-8601'}, - 'file_name': {'key': 'properties.fileName', 'type': 'str'}, - 'run_settings': {'key': 'properties.runSettings', 'type': 'CommonExportProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportExecution, self).__init__(**kwargs) - self.execution_type = kwargs.get('execution_type', None) - self.status = kwargs.get('status', None) - self.submitted_by = kwargs.get('submitted_by', None) - self.submitted_time = kwargs.get('submitted_time', None) - self.processing_start_time = kwargs.get('processing_start_time', None) - self.processing_end_time = kwargs.get('processing_end_time', None) - self.file_name = kwargs.get('file_name', None) - self.run_settings = kwargs.get('run_settings', None) - - -class ExportExecutionListResult(msrest.serialization.Model): - """Result of listing exports execution history of a export by name. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of export executions. - :vartype value: list[~azure.mgmt.costmanagement.models.ExportExecution] - """ - - _validation = { - 'value': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[ExportExecution]'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportExecutionListResult, self).__init__(**kwargs) - self.value = None - - -class ExportListResult(msrest.serialization.Model): - """Result of listing exports. It contains a list of available exports in the scope provided. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of exports. - :vartype value: list[~azure.mgmt.costmanagement.models.Export] - """ - - _validation = { - 'value': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Export]'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportListResult, self).__init__(**kwargs) - self.value = None - - -class ExportProperties(CommonExportProperties): - """The properties of the export. - - All required parameters must be populated in order to send to Azure. - - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule - """ - - _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, - } - - _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'schedule', 'type': 'ExportSchedule'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportProperties, self).__init__(**kwargs) - self.schedule = kwargs.get('schedule', None) - - -class ExportRecurrencePeriod(msrest.serialization.Model): - """The start and end date for recurrence schedule. - - All required parameters must be populated in order to send to Azure. - - :param from_property: Required. The start date of recurrence. - :type from_property: ~datetime.datetime - :param to: The end date of recurrence. - :type to: ~datetime.datetime - """ - - _validation = { - 'from_property': {'required': True}, - } - - _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportRecurrencePeriod, self).__init__(**kwargs) - self.from_property = kwargs['from_property'] - self.to = kwargs.get('to', None) - - -class ExportSchedule(msrest.serialization.Model): - """The schedule associated with a export. - - All required parameters must be populated in order to send to Azure. - - :param status: The status of the schedule. Whether active or not. If inactive, the export's - scheduled execution is paused. Possible values include: "Active", "Inactive". - :type status: str or ~azure.mgmt.costmanagement.models.StatusType - :param recurrence: Required. The schedule recurrence. Possible values include: "Daily", - "Weekly", "Monthly", "Annually". - :type recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType - :param recurrence_period: Has start and end date of the recurrence. The start date must be in - future. If present, the end date must be greater than start date. - :type recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod - """ - - _validation = { - 'recurrence': {'required': True}, - } - - _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'recurrence': {'key': 'recurrence', 'type': 'str'}, - 'recurrence_period': {'key': 'recurrencePeriod', 'type': 'ExportRecurrencePeriod'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportSchedule, self).__init__(**kwargs) - self.status = kwargs.get('status', None) - self.recurrence = kwargs['recurrence'] - self.recurrence_period = kwargs.get('recurrence_period', None) - - -class ForecastDefinition(msrest.serialization.Model): - """The definition of a forecast. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of the forecast. Possible values include: "Usage", - "ActualCost", "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ForecastType - :param timeframe: Required. The time frame for pulling data for the forecast. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframeType - :param time_period: Has time period for pulling data for the forecast. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this forecast. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset - :param include_actual_cost: a boolean determining if actualCost will be included. - :type include_actual_cost: bool - :param include_fresh_partial_cost: a boolean determining if FreshPartialCost will be included. - :type include_fresh_partial_cost: bool - """ - - _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, - 'include_actual_cost': {'key': 'includeActualCost', 'type': 'bool'}, - 'include_fresh_partial_cost': {'key': 'includeFreshPartialCost', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(ForecastDefinition, self).__init__(**kwargs) - self.type = kwargs['type'] - self.timeframe = kwargs['timeframe'] - self.time_period = kwargs.get('time_period', None) - self.dataset = kwargs['dataset'] - self.include_actual_cost = kwargs.get('include_actual_cost', None) - self.include_fresh_partial_cost = kwargs.get('include_fresh_partial_cost', None) - - -class KpiProperties(msrest.serialization.Model): - """Each KPI must contain a 'type' and 'enabled' key. - - :param type: KPI type (Forecast, Budget). Possible values include: "Forecast", "Budget". - :type type: str or ~azure.mgmt.costmanagement.models.KpiType - :param id: ID of resource related to metric (budget). - :type id: str - :param enabled: show the KPI in the UI?. - :type enabled: bool - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'enabled': {'key': 'enabled', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(KpiProperties, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.id = kwargs.get('id', None) - self.enabled = kwargs.get('enabled', None) - - -class Operation(msrest.serialization.Model): - """A Cost management REST API operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :param display: The object that represents the operation. - :type display: ~azure.mgmt.costmanagement.models.OperationDisplay - """ - - _validation = { - 'name': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = None - self.display = kwargs.get('display', None) - - -class OperationDisplay(msrest.serialization.Model): - """The object that represents the operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: Service provider: Microsoft.CostManagement. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Dimensions, Query. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - """ - - _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - } - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - - -class OperationListResult(msrest.serialization.Model): - """Result of listing cost management operations. It contains a list of operations and a URL link to get the next set of results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of cost management operations supported by the Microsoft.CostManagement - resource provider. - :vartype value: list[~azure.mgmt.costmanagement.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class OperationStatus(msrest.serialization.Model): - """The status of the long running operation. - - :param status: The status of the long running operation. - :type status: ~azure.mgmt.costmanagement.models.Status - :param report_url: The URL to download the generated report. - :type report_url: str - :param valid_until: The time at which report URL becomes invalid. - :type valid_until: ~datetime.datetime - """ - - _attribute_map = { - 'status': {'key': 'status', 'type': 'Status'}, - 'report_url': {'key': 'properties.reportUrl', 'type': 'str'}, - 'valid_until': {'key': 'properties.validUntil', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationStatus, self).__init__(**kwargs) - self.status = kwargs.get('status', None) - self.report_url = kwargs.get('report_url', None) - self.valid_until = kwargs.get('valid_until', None) - - -class PivotProperties(msrest.serialization.Model): - """Each pivot must contain a 'type' and 'name'. - - :param type: Data type to show in view. Possible values include: "Dimension", "TagKey". - :type type: str or ~azure.mgmt.costmanagement.models.PivotType - :param name: Data field to show in view. - :type name: str - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PivotProperties, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.name = kwargs.get('name', None) - - -class ProxySettingResource(msrest.serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str - :ivar type: Resource type. - :vartype type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ProxySettingResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.kind = None - self.type = None - - -class QueryAggregation(msrest.serialization.Model): - """The aggregation expression to be used in the query. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType - """ - - _validation = { - 'name': {'required': True}, - 'function': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryAggregation, self).__init__(**kwargs) - self.name = kwargs['name'] - self.function = kwargs['function'] - - -class QueryColumn(msrest.serialization.Model): - """QueryColumn. - - :param name: The name of column. - :type name: str - :param type: The type of column. - :type type: str - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryColumn, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.type = kwargs.get('type', None) - - -class QueryComparisonExpression(msrest.serialization.Model): - """The comparison expression to be used in the query. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", - "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] - """ - - _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryComparisonExpression, self).__init__(**kwargs) - self.name = kwargs['name'] - self.operator = kwargs['operator'] - self.values = kwargs['values'] - - -class QueryDataset(msrest.serialization.Model): - """The definition of data present in the query. - - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each - item in the dictionary is the alias for the aggregated column. Query can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group - by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST - documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilter - """ - - _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, - } - - _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilter'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDataset, self).__init__(**kwargs) - self.granularity = kwargs.get('granularity', None) - self.configuration = kwargs.get('configuration', None) - self.aggregation = kwargs.get('aggregation', None) - self.grouping = kwargs.get('grouping', None) - self.filter = kwargs.get('filter', None) - - -class QueryDatasetAutoGenerated(msrest.serialization.Model): - """The definition of data present in the query. - - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each - item in the dictionary is the alias for the aggregated column. Query can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group - by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST - documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated - """ - - _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, - } - - _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilterAutoGenerated'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDatasetAutoGenerated, self).__init__(**kwargs) - self.granularity = kwargs.get('granularity', None) - self.configuration = kwargs.get('configuration', None) - self.aggregation = kwargs.get('aggregation', None) - self.grouping = kwargs.get('grouping', None) - self.filter = kwargs.get('filter', None) - - -class QueryDatasetConfiguration(msrest.serialization.Model): - """The configuration of dataset in the query. - - :param columns: Array of column names to be included in the query. Any valid query column name - is allowed. If not provided, then query includes all columns. - :type columns: list[str] - """ - - _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDatasetConfiguration, self).__init__(**kwargs) - self.columns = kwargs.get('columns', None) - - -class QueryDefinition(msrest.serialization.Model): - """The definition of a query. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", - "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this query. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset - """ - - _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDefinition, self).__init__(**kwargs) - self.type = kwargs['type'] - self.timeframe = kwargs['timeframe'] - self.time_period = kwargs.get('time_period', None) - self.dataset = kwargs['dataset'] - - -class QueryFilter(msrest.serialization.Model): - """The filter expression to be used in the export. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilter]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryFilter, self).__init__(**kwargs) - self.and_property = kwargs.get('and_property', None) - self.or_property = kwargs.get('or_property', None) - self.dimensions = kwargs.get('dimensions', None) - self.tags = kwargs.get('tags', None) - - -class QueryFilterAutoGenerated(msrest.serialization.Model): - """The filter expression to be used in the export. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilterAutoGenerated]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilterAutoGenerated]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryFilterAutoGenerated, self).__init__(**kwargs) - self.and_property = kwargs.get('and_property', None) - self.or_property = kwargs.get('or_property', None) - self.dimensions = kwargs.get('dimensions', None) - self.tags = kwargs.get('tags', None) - - -class QueryGrouping(msrest.serialization.Model): - """The group by expression to be used in the query. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.QueryColumnType - :param name: Required. The name of the column to group. - :type name: str - """ - - _validation = { - 'type': {'required': True}, - 'name': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryGrouping, self).__init__(**kwargs) - self.type = kwargs['type'] - self.name = kwargs['name'] - - -class QueryResult(Resource): - """Result of query. It contains all columns listed under groupings and aggregation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :ivar location: Resource location. - :vartype location: str - :ivar sku: Resource SKU. - :vartype sku: str - :param next_link: The link (url) to the next page of results. - :type next_link: str - :param columns: Array of columns. - :type columns: list[~azure.mgmt.costmanagement.models.QueryColumn] - :param rows: Array of rows. - :type rows: list[list[any]] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'location': {'readonly': True}, - 'sku': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - 'columns': {'key': 'properties.columns', 'type': '[QueryColumn]'}, - 'rows': {'key': 'properties.rows', 'type': '[[object]]'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryResult, self).__init__(**kwargs) - self.e_tag = kwargs.get('e_tag', None) - self.location = None - self.sku = None - self.next_link = kwargs.get('next_link', None) - self.columns = kwargs.get('columns', None) - self.rows = kwargs.get('rows', None) - - -class QueryTimePeriod(msrest.serialization.Model): - """The start and end date for pulling data for the query. - - All required parameters must be populated in order to send to Azure. - - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime - """ - - _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, - } - - _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryTimePeriod, self).__init__(**kwargs) - self.from_property = kwargs['from_property'] - self.to = kwargs['to'] - - -class ReportConfigAggregation(msrest.serialization.Model): - """The aggregation expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType - """ - - _validation = { - 'name': {'required': True}, - 'function': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigAggregation, self).__init__(**kwargs) - self.name = kwargs['name'] - self.function = kwargs['function'] - - -class ReportConfigComparisonExpression(msrest.serialization.Model): - """The comparison expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", - "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] - """ - - _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigComparisonExpression, self).__init__(**kwargs) - self.name = kwargs['name'] - self.operator = kwargs['operator'] - self.values = kwargs['values'] - - -class ReportConfigDataset(msrest.serialization.Model): - """The definition of data present in the report. - - :param granularity: The granularity of rows in the report. Possible values include: "Daily", - "Monthly". - :type granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType - :param configuration: Has configuration information for the data in the report. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the report. The key of each - item in the dictionary is the alias for the aggregated column. Report can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] - :param grouping: Array of group by expression to use in the report. Report can have up to 2 - group by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] - :param sorting: Array of order by expression to use in the report. - :type sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] - :param filter: Has filter expression to use in the report. - :type filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter - """ - - _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, - } - - _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'ReportConfigDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{ReportConfigAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[ReportConfigGrouping]'}, - 'sorting': {'key': 'sorting', 'type': '[ReportConfigSorting]'}, - 'filter': {'key': 'filter', 'type': 'ReportConfigFilter'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigDataset, self).__init__(**kwargs) - self.granularity = kwargs.get('granularity', None) - self.configuration = kwargs.get('configuration', None) - self.aggregation = kwargs.get('aggregation', None) - self.grouping = kwargs.get('grouping', None) - self.sorting = kwargs.get('sorting', None) - self.filter = kwargs.get('filter', None) - - -class ReportConfigDatasetConfiguration(msrest.serialization.Model): - """The configuration of dataset in the report. - - :param columns: Array of column names to be included in the report. Any valid report column - name is allowed. If not provided, then report includes all columns. - :type columns: list[str] - """ - - _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigDatasetConfiguration, self).__init__(**kwargs) - self.columns = kwargs.get('columns', None) - - -class ReportConfigFilter(msrest.serialization.Model): - """The filter expression to be used in the report. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_key: Has comparison expression for a tag key. - :type tag_key: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_value: Has comparison expression for a tag value. - :type tag_value: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[ReportConfigFilter]'}, - 'or_property': {'key': 'or', 'type': '[ReportConfigFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'ReportConfigComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'ReportConfigComparisonExpression'}, - 'tag_key': {'key': 'tagKey', 'type': 'ReportConfigComparisonExpression'}, - 'tag_value': {'key': 'tagValue', 'type': 'ReportConfigComparisonExpression'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigFilter, self).__init__(**kwargs) - self.and_property = kwargs.get('and_property', None) - self.or_property = kwargs.get('or_property', None) - self.dimensions = kwargs.get('dimensions', None) - self.tags = kwargs.get('tags', None) - self.tag_key = kwargs.get('tag_key', None) - self.tag_value = kwargs.get('tag_value', None) - - -class ReportConfigGrouping(msrest.serialization.Model): - """The group by expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType - :param name: Required. The name of the column to group. This version supports subscription - lowest possible grain. - :type name: str - """ - - _validation = { - 'type': {'required': True}, - 'name': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigGrouping, self).__init__(**kwargs) - self.type = kwargs['type'] - self.name = kwargs['name'] - - -class ReportConfigSorting(msrest.serialization.Model): - """The order by expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param direction: Direction of sort. Possible values include: "Ascending", "Descending". - :type direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingDirection - :param name: Required. The name of the column to sort. - :type name: str - """ - - _validation = { - 'name': {'required': True}, - } - - _attribute_map = { - 'direction': {'key': 'direction', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigSorting, self).__init__(**kwargs) - self.direction = kwargs.get('direction', None) - self.name = kwargs['name'] - - -class ReportConfigTimePeriod(msrest.serialization.Model): - """The start and end date for pulling data for the report. - - All required parameters must be populated in order to send to Azure. - - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime - """ - - _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, - } - - _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigTimePeriod, self).__init__(**kwargs) - self.from_property = kwargs['from_property'] - self.to = kwargs['to'] - - -class Setting(ProxySettingResource): - """State of the myscope setting. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str - :ivar type: Resource type. - :vartype type: str - :param scope: Sets the default scope the current user will see when they sign into Azure Cost - Management in the Azure portal. - :type scope: str - :param start_on: Indicates what scope Cost Management in the Azure portal should default to. - Allowed values: LastUsed. Possible values include: "LastUsed", "ScopePicker", "SpecificScope". - :type start_on: str or ~azure.mgmt.costmanagement.models.SettingsPropertiesStartOn - :param cache: Array of scopes with additional details used by Cost Management in the Azure - portal. - :type cache: list[~azure.mgmt.costmanagement.models.CacheItem] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'start_on': {'key': 'properties.startOn', 'type': 'str'}, - 'cache': {'key': 'properties.cache', 'type': '[CacheItem]'}, - } - - def __init__( - self, - **kwargs - ): - super(Setting, self).__init__(**kwargs) - self.scope = kwargs.get('scope', None) - self.start_on = kwargs.get('start_on', None) - self.cache = kwargs.get('cache', None) - - -class SettingsListResult(msrest.serialization.Model): - """Result of listing settings. It contains a list of available settings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of settings. - :vartype value: list[~azure.mgmt.costmanagement.models.Setting] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True, 'max_items': 10, 'min_items': 0}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Setting]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SettingsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class Status(msrest.serialization.Model): - """The status of the long running operation. - - :param status: The status of the long running operation. Possible values include: "Running", - "Completed", "Failed". - :type status: str or ~azure.mgmt.costmanagement.models.OperationStatusType - """ - - _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Status, self).__init__(**kwargs) - self.status = kwargs.get('status', None) - - -class View(ProxyResource): - """States and configurations of Cost Analysis. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param display_name: User input name of the view. Required. - :type display_name: str - :param scope: Cost Management scope to save the view on. This includes - 'subscriptions/{subscriptionId}' for subscription scope, - 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for - Department scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' - for EnrollmentAccount scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for BillingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' - for Management Group scope, - '/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for - ExternalBillingAccount scope, and - '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - ExternalSubscription scope. - :type scope: str - :ivar created_on: Date the user created this view. - :vartype created_on: ~datetime.datetime - :ivar modified_on: Date when the user last modified this view. - :vartype modified_on: ~datetime.datetime - :ivar date_range: Selected date range for viewing cost in. - :vartype date_range: str - :ivar currency: Selected currency. - :vartype currency: str - :param chart: Chart type of the main view in Cost Analysis. Required. Possible values include: - "Area", "Line", "StackedColumn", "GroupedColumn", "Table". - :type chart: str or ~azure.mgmt.costmanagement.models.ChartType - :param accumulated: Show costs accumulated over time. Possible values include: "true", "false". - :type accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType - :param metric: Metric to use when displaying costs. Possible values include: "ActualCost", - "AmortizedCost", "AHUB". - :type metric: str or ~azure.mgmt.costmanagement.models.MetricType - :param kpis: List of KPIs to show in Cost Analysis UI. - :type kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] - :param pivots: Configuration of 3 sub-views in the Cost Analysis UI. - :type pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] - :param type_properties_query_type: The type of the report. Usage represents actual usage, - forecast represents forecasted data and UsageAndForecast represents both usage and forecasted - data. Actual usage and forecasted data can be differentiated based on dates. Possible values - include: "Usage". - :type type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType - :param timeframe: The time frame for pulling data for the report. If custom, then a specific - time period must be provided. Possible values include: "WeekToDate", "MonthToDate", - "YearToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType - :param time_period: Has time period for pulling data for the report. - :type time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod - :param data_set: Has definition for data in this report config. - :type data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset - :ivar include_monetary_commitment: Include monetary commitment. - :vartype include_monetary_commitment: bool - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'created_on': {'readonly': True}, - 'modified_on': {'readonly': True}, - 'date_range': {'readonly': True}, - 'currency': {'readonly': True}, - 'include_monetary_commitment': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'modified_on': {'key': 'properties.modifiedOn', 'type': 'iso-8601'}, - 'date_range': {'key': 'properties.dateRange', 'type': 'str'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'chart': {'key': 'properties.chart', 'type': 'str'}, - 'accumulated': {'key': 'properties.accumulated', 'type': 'str'}, - 'metric': {'key': 'properties.metric', 'type': 'str'}, - 'kpis': {'key': 'properties.kpis', 'type': '[KpiProperties]'}, - 'pivots': {'key': 'properties.pivots', 'type': '[PivotProperties]'}, - 'type_properties_query_type': {'key': 'properties.query.type', 'type': 'str'}, - 'timeframe': {'key': 'properties.query.timeframe', 'type': 'str'}, - 'time_period': {'key': 'properties.query.timePeriod', 'type': 'ReportConfigTimePeriod'}, - 'data_set': {'key': 'properties.query.dataSet', 'type': 'ReportConfigDataset'}, - 'include_monetary_commitment': {'key': 'properties.query.includeMonetaryCommitment', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(View, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.scope = kwargs.get('scope', None) - self.created_on = None - self.modified_on = None - self.date_range = None - self.currency = None - self.chart = kwargs.get('chart', None) - self.accumulated = kwargs.get('accumulated', None) - self.metric = kwargs.get('metric', None) - self.kpis = kwargs.get('kpis', None) - self.pivots = kwargs.get('pivots', None) - self.type_properties_query_type = kwargs.get('type_properties_query_type', None) - self.timeframe = kwargs.get('timeframe', None) - self.time_period = kwargs.get('time_period', None) - self.data_set = kwargs.get('data_set', None) - self.include_monetary_commitment = None - - -class ViewListResult(msrest.serialization.Model): - """Result of listing views. It contains a list of available views. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of views. - :vartype value: list[~azure.mgmt.costmanagement.models.View] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[View]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ViewListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py index e3f7e70197dd..9a784e5fdf72 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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 ._cost_management_client_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 Resource(msrest.serialization.Model): +class ProxyResource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -26,36 +34,38 @@ class Resource(msrest.serialization.Model): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'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'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + } + + def __init__(self, *, e_tag: Optional[str] = None, **kwargs): + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None - self.tags = None + self.e_tag = e_tag -class Alert(Resource): +class Alert(ProxyResource): # pylint: disable=too-many-instance-attributes """An individual alert. Variables are only populated by the server, and will be ignored when sending a request. @@ -66,67 +76,68 @@ class Alert(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str + :ivar definition: defines the type of alert. + :vartype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :ivar description: Alert description. + :vartype description: str + :ivar source: Source of alert. Known values are: "Preset" and "User". + :vartype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :ivar details: Alert details. + :vartype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :ivar cost_entity_id: related budget. + :vartype cost_entity_id: str + :ivar status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", and + "Dismissed". + :vartype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :ivar creation_time: dateTime in which alert was created. + :vartype creation_time: str + :ivar close_time: dateTime in which alert was closed. + :vartype close_time: str + :ivar modification_time: dateTime in which alert was last modified. + :vartype modification_time: str + :ivar status_modification_user_name: User who last modified the alert. + :vartype status_modification_user_name: str + :ivar status_modification_time: dateTime in which the alert status was last modified. + :vartype status_modification_time: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, + "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"}, + "e_tag": {"key": "eTag", "type": "str"}, + "definition": {"key": "properties.definition", "type": "AlertPropertiesDefinition"}, + "description": {"key": "properties.description", "type": "str"}, + "source": {"key": "properties.source", "type": "str"}, + "details": {"key": "properties.details", "type": "AlertPropertiesDetails"}, + "cost_entity_id": {"key": "properties.costEntityId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "creation_time": {"key": "properties.creationTime", "type": "str"}, + "close_time": {"key": "properties.closeTime", "type": "str"}, + "modification_time": {"key": "properties.modificationTime", "type": "str"}, + "status_modification_user_name": {"key": "properties.statusModificationUserName", "type": "str"}, + "status_modification_time": {"key": "properties.statusModificationTime", "type": "str"}, } def __init__( self, *, - definition: Optional["AlertPropertiesDefinition"] = None, + e_tag: Optional[str] = None, + definition: Optional["_models.AlertPropertiesDefinition"] = None, description: Optional[str] = None, - source: Optional[Union[str, "AlertSource"]] = None, - details: Optional["AlertPropertiesDetails"] = None, + source: Optional[Union[str, "_models.AlertSource"]] = None, + details: Optional["_models.AlertPropertiesDetails"] = None, cost_entity_id: Optional[str] = None, - status: Optional[Union[str, "AlertStatus"]] = None, + status: Optional[Union[str, "_models.AlertStatus"]] = None, creation_time: Optional[str] = None, close_time: Optional[str] = None, modification_time: Optional[str] = None, @@ -134,7 +145,35 @@ def __init__( status_modification_time: Optional[str] = None, **kwargs ): - super(Alert, self).__init__(**kwargs) + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword definition: defines the type of alert. + :paramtype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :keyword description: Alert description. + :paramtype description: str + :keyword source: Source of alert. Known values are: "Preset" and "User". + :paramtype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :keyword details: Alert details. + :paramtype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :keyword cost_entity_id: related budget. + :paramtype cost_entity_id: str + :keyword status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", + and "Dismissed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :keyword creation_time: dateTime in which alert was created. + :paramtype creation_time: str + :keyword close_time: dateTime in which alert was closed. + :paramtype close_time: str + :keyword modification_time: dateTime in which alert was last modified. + :paramtype modification_time: str + :keyword status_modification_user_name: User who last modified the alert. + :paramtype status_modification_user_name: str + :keyword status_modification_time: dateTime in which the alert status was last modified. + :paramtype status_modification_time: str + """ + super().__init__(e_tag=e_tag, **kwargs) self.definition = definition self.description = description self.source = source @@ -148,113 +187,145 @@ def __init__( self.status_modification_time = status_modification_time -class AlertPropertiesDefinition(msrest.serialization.Model): +class AlertPropertiesDefinition(_serialization.Model): """defines the type of alert. - :param type: type of alert. Possible values include: "Budget", "Invoice", "Credit", "Quota", - "General", "xCloud", "BudgetForecast". - :type type: str or ~azure.mgmt.costmanagement.models.AlertType - :param category: Alert category. Possible values include: "Cost", "Usage", "Billing", "System". - :type category: str or ~azure.mgmt.costmanagement.models.AlertCategory - :param criteria: Criteria that triggered alert. Possible values include: - "CostThresholdExceeded", "UsageThresholdExceeded", "CreditThresholdApproaching", - "CreditThresholdReached", "QuotaThresholdApproaching", "QuotaThresholdReached", - "MultiCurrency", "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", - "InvoiceDueDateApproaching", "InvoiceDueDateReached", "CrossCloudNewDataAvailable", - "CrossCloudCollectionError", "GeneralThresholdError". - :type criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria + :ivar type: type of alert. Known values are: "Budget", "Invoice", "Credit", "Quota", "General", + "xCloud", and "BudgetForecast". + :vartype type: str or ~azure.mgmt.costmanagement.models.AlertType + :ivar category: Alert category. Known values are: "Cost", "Usage", "Billing", and "System". + :vartype category: str or ~azure.mgmt.costmanagement.models.AlertCategory + :ivar criteria: Criteria that triggered alert. Known values are: "CostThresholdExceeded", + "UsageThresholdExceeded", "CreditThresholdApproaching", "CreditThresholdReached", + "QuotaThresholdApproaching", "QuotaThresholdReached", "MultiCurrency", + "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", "InvoiceDueDateApproaching", + "InvoiceDueDateReached", "CrossCloudNewDataAvailable", "CrossCloudCollectionError", and + "GeneralThresholdError". + :vartype criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'criteria': {'key': 'criteria', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "criteria": {"key": "criteria", "type": "str"}, } def __init__( self, *, - type: Optional[Union[str, "AlertType"]] = None, - category: Optional[Union[str, "AlertCategory"]] = None, - criteria: Optional[Union[str, "AlertCriteria"]] = None, + type: Optional[Union[str, "_models.AlertType"]] = None, + category: Optional[Union[str, "_models.AlertCategory"]] = None, + criteria: Optional[Union[str, "_models.AlertCriteria"]] = None, **kwargs ): - super(AlertPropertiesDefinition, self).__init__(**kwargs) + """ + :keyword type: type of alert. Known values are: "Budget", "Invoice", "Credit", "Quota", + "General", "xCloud", and "BudgetForecast". + :paramtype type: str or ~azure.mgmt.costmanagement.models.AlertType + :keyword category: Alert category. Known values are: "Cost", "Usage", "Billing", and "System". + :paramtype category: str or ~azure.mgmt.costmanagement.models.AlertCategory + :keyword criteria: Criteria that triggered alert. Known values are: "CostThresholdExceeded", + "UsageThresholdExceeded", "CreditThresholdApproaching", "CreditThresholdReached", + "QuotaThresholdApproaching", "QuotaThresholdReached", "MultiCurrency", + "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", "InvoiceDueDateApproaching", + "InvoiceDueDateReached", "CrossCloudNewDataAvailable", "CrossCloudCollectionError", and + "GeneralThresholdError". + :paramtype criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria + """ + super().__init__(**kwargs) self.type = type self.category = category self.criteria = criteria -class AlertPropertiesDetails(msrest.serialization.Model): +class AlertPropertiesDetails(_serialization.Model): # pylint: disable=too-many-instance-attributes """Alert details. - :param time_grain_type: Type of timegrain cadence. Possible values include: "None", "Monthly", - "Quarterly", "Annually", "BillingMonth", "BillingQuarter", "BillingAnnual". - :type time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType - :param period_start_date: datetime of periodStartDate. - :type period_start_date: str - :param triggered_by: notificationId that triggered this alert. - :type triggered_by: str - :param resource_group_filter: array of resourceGroups to filter by. - :type resource_group_filter: list[any] - :param resource_filter: array of resources to filter by. - :type resource_filter: list[any] - :param meter_filter: array of meters to filter by. - :type meter_filter: list[any] - :param tag_filter: tags to filter by. - :type tag_filter: any - :param threshold: notification threshold percentage as a decimal which activated this alert. - :type threshold: float - :param operator: operator used to compare currentSpend with amount. Possible values include: - "None", "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", "LessThanOrEqualTo". - :type operator: str or ~azure.mgmt.costmanagement.models.AlertOperator - :param amount: budget threshold amount. - :type amount: float - :param unit: unit of currency being used. - :type unit: str - :param current_spend: current spend. - :type current_spend: float - :param contact_emails: list of emails to contact. - :type contact_emails: list[str] - :param contact_groups: list of action groups to broadcast to. - :type contact_groups: list[str] - :param contact_roles: list of contact roles. - :type contact_roles: list[str] - :param overriding_alert: overriding alert. - :type overriding_alert: str - """ - - _attribute_map = { - 'time_grain_type': {'key': 'timeGrainType', 'type': 'str'}, - 'period_start_date': {'key': 'periodStartDate', 'type': 'str'}, - 'triggered_by': {'key': 'triggeredBy', 'type': 'str'}, - 'resource_group_filter': {'key': 'resourceGroupFilter', 'type': '[object]'}, - 'resource_filter': {'key': 'resourceFilter', 'type': '[object]'}, - 'meter_filter': {'key': 'meterFilter', 'type': '[object]'}, - 'tag_filter': {'key': 'tagFilter', 'type': 'object'}, - 'threshold': {'key': 'threshold', 'type': 'float'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'current_spend': {'key': 'currentSpend', 'type': 'float'}, - 'contact_emails': {'key': 'contactEmails', 'type': '[str]'}, - 'contact_groups': {'key': 'contactGroups', 'type': '[str]'}, - 'contact_roles': {'key': 'contactRoles', 'type': '[str]'}, - 'overriding_alert': {'key': 'overridingAlert', 'type': 'str'}, + :ivar time_grain_type: Type of timegrain cadence. Known values are: "None", "Monthly", + "Quarterly", "Annually", "BillingMonth", "BillingQuarter", and "BillingAnnual". + :vartype time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType + :ivar period_start_date: datetime of periodStartDate. + :vartype period_start_date: str + :ivar triggered_by: notificationId that triggered this alert. + :vartype triggered_by: str + :ivar resource_group_filter: array of resourceGroups to filter by. + :vartype resource_group_filter: list[any] + :ivar resource_filter: array of resources to filter by. + :vartype resource_filter: list[any] + :ivar meter_filter: array of meters to filter by. + :vartype meter_filter: list[any] + :ivar tag_filter: tags to filter by. + :vartype tag_filter: JSON + :ivar threshold: notification threshold percentage as a decimal which activated this alert. + :vartype threshold: float + :ivar operator: operator used to compare currentSpend with amount. Known values are: "None", + "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", and "LessThanOrEqualTo". + :vartype operator: str or ~azure.mgmt.costmanagement.models.AlertOperator + :ivar amount: budget threshold amount. + :vartype amount: float + :ivar unit: unit of currency being used. + :vartype unit: str + :ivar current_spend: current spend. + :vartype current_spend: float + :ivar contact_emails: list of emails to contact. + :vartype contact_emails: list[str] + :ivar contact_groups: list of action groups to broadcast to. + :vartype contact_groups: list[str] + :ivar contact_roles: list of contact roles. + :vartype contact_roles: list[str] + :ivar overriding_alert: overriding alert. + :vartype overriding_alert: str + :ivar department_name: department name. + :vartype department_name: str + :ivar company_name: company name. + :vartype company_name: str + :ivar enrollment_number: enrollment number. + :vartype enrollment_number: str + :ivar enrollment_start_date: datetime of enrollmentStartDate. + :vartype enrollment_start_date: str + :ivar enrollment_end_date: datetime of enrollmentEndDate. + :vartype enrollment_end_date: str + :ivar invoicing_threshold: invoicing threshold. + :vartype invoicing_threshold: float + """ + + _attribute_map = { + "time_grain_type": {"key": "timeGrainType", "type": "str"}, + "period_start_date": {"key": "periodStartDate", "type": "str"}, + "triggered_by": {"key": "triggeredBy", "type": "str"}, + "resource_group_filter": {"key": "resourceGroupFilter", "type": "[object]"}, + "resource_filter": {"key": "resourceFilter", "type": "[object]"}, + "meter_filter": {"key": "meterFilter", "type": "[object]"}, + "tag_filter": {"key": "tagFilter", "type": "object"}, + "threshold": {"key": "threshold", "type": "float"}, + "operator": {"key": "operator", "type": "str"}, + "amount": {"key": "amount", "type": "float"}, + "unit": {"key": "unit", "type": "str"}, + "current_spend": {"key": "currentSpend", "type": "float"}, + "contact_emails": {"key": "contactEmails", "type": "[str]"}, + "contact_groups": {"key": "contactGroups", "type": "[str]"}, + "contact_roles": {"key": "contactRoles", "type": "[str]"}, + "overriding_alert": {"key": "overridingAlert", "type": "str"}, + "department_name": {"key": "departmentName", "type": "str"}, + "company_name": {"key": "companyName", "type": "str"}, + "enrollment_number": {"key": "enrollmentNumber", "type": "str"}, + "enrollment_start_date": {"key": "enrollmentStartDate", "type": "str"}, + "enrollment_end_date": {"key": "enrollmentEndDate", "type": "str"}, + "invoicing_threshold": {"key": "invoicingThreshold", "type": "float"}, } def __init__( self, *, - time_grain_type: Optional[Union[str, "AlertTimeGrainType"]] = None, + time_grain_type: Optional[Union[str, "_models.AlertTimeGrainType"]] = None, period_start_date: Optional[str] = None, triggered_by: Optional[str] = None, resource_group_filter: Optional[List[Any]] = None, resource_filter: Optional[List[Any]] = None, meter_filter: Optional[List[Any]] = None, - tag_filter: Optional[Any] = None, + tag_filter: Optional[JSON] = None, threshold: Optional[float] = None, - operator: Optional[Union[str, "AlertOperator"]] = None, + operator: Optional[Union[str, "_models.AlertOperator"]] = None, amount: Optional[float] = None, unit: Optional[str] = None, current_spend: Optional[float] = None, @@ -262,9 +333,63 @@ def __init__( contact_groups: Optional[List[str]] = None, contact_roles: Optional[List[str]] = None, overriding_alert: Optional[str] = None, + department_name: Optional[str] = None, + company_name: Optional[str] = None, + enrollment_number: Optional[str] = None, + enrollment_start_date: Optional[str] = None, + enrollment_end_date: Optional[str] = None, + invoicing_threshold: Optional[float] = None, **kwargs ): - super(AlertPropertiesDetails, self).__init__(**kwargs) + """ + :keyword time_grain_type: Type of timegrain cadence. Known values are: "None", "Monthly", + "Quarterly", "Annually", "BillingMonth", "BillingQuarter", and "BillingAnnual". + :paramtype time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType + :keyword period_start_date: datetime of periodStartDate. + :paramtype period_start_date: str + :keyword triggered_by: notificationId that triggered this alert. + :paramtype triggered_by: str + :keyword resource_group_filter: array of resourceGroups to filter by. + :paramtype resource_group_filter: list[any] + :keyword resource_filter: array of resources to filter by. + :paramtype resource_filter: list[any] + :keyword meter_filter: array of meters to filter by. + :paramtype meter_filter: list[any] + :keyword tag_filter: tags to filter by. + :paramtype tag_filter: JSON + :keyword threshold: notification threshold percentage as a decimal which activated this alert. + :paramtype threshold: float + :keyword operator: operator used to compare currentSpend with amount. Known values are: "None", + "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", and "LessThanOrEqualTo". + :paramtype operator: str or ~azure.mgmt.costmanagement.models.AlertOperator + :keyword amount: budget threshold amount. + :paramtype amount: float + :keyword unit: unit of currency being used. + :paramtype unit: str + :keyword current_spend: current spend. + :paramtype current_spend: float + :keyword contact_emails: list of emails to contact. + :paramtype contact_emails: list[str] + :keyword contact_groups: list of action groups to broadcast to. + :paramtype contact_groups: list[str] + :keyword contact_roles: list of contact roles. + :paramtype contact_roles: list[str] + :keyword overriding_alert: overriding alert. + :paramtype overriding_alert: str + :keyword department_name: department name. + :paramtype department_name: str + :keyword company_name: company name. + :paramtype company_name: str + :keyword enrollment_number: enrollment number. + :paramtype enrollment_number: str + :keyword enrollment_start_date: datetime of enrollmentStartDate. + :paramtype enrollment_start_date: str + :keyword enrollment_end_date: datetime of enrollmentEndDate. + :paramtype enrollment_end_date: str + :keyword invoicing_threshold: invoicing threshold. + :paramtype invoicing_threshold: float + """ + super().__init__(**kwargs) self.time_grain_type = time_grain_type self.period_start_date = period_start_date self.triggered_by = triggered_by @@ -281,9 +406,15 @@ def __init__( self.contact_groups = contact_groups self.contact_roles = contact_roles self.overriding_alert = overriding_alert + self.department_name = department_name + self.company_name = company_name + self.enrollment_number = enrollment_number + self.enrollment_start_date = enrollment_start_date + self.enrollment_end_date = enrollment_end_date + self.invoicing_threshold = invoicing_threshold -class AlertsResult(msrest.serialization.Model): +class AlertsResult(_serialization.Model): """Result of alerts. Variables are only populated by the server, and will be ignored when sending a request. @@ -295,123 +426,335 @@ class AlertsResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Alert]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Alert]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(AlertsResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class CacheItem(msrest.serialization.Model): - """CacheItem. +class BlobInfo(_serialization.Model): + """The blob information generated by this operation. + + :ivar blob_link: Link to the blob to download file. + :vartype blob_link: str + :ivar byte_count: Bytes in the blob. + :vartype byte_count: int + """ + + _attribute_map = { + "blob_link": {"key": "blobLink", "type": "str"}, + "byte_count": {"key": "byteCount", "type": "int"}, + } + + def __init__(self, *, blob_link: Optional[str] = None, byte_count: Optional[int] = None, **kwargs): + """ + :keyword blob_link: Link to the blob to download file. + :paramtype blob_link: str + :keyword byte_count: Bytes in the blob. + :paramtype byte_count: int + """ + super().__init__(**kwargs) + self.blob_link = blob_link + self.byte_count = byte_count + + +class CommonExportProperties(_serialization.Model): + """The common properties of the export. + + Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :param id: Required. Resource ID used by Resource Manager to uniquely identify the scope. - :type id: str - :param name: Required. Display name for the scope. - :type name: str - :param channel: Required. Indicates the account type. Allowed values include: EA, PAYG, Modern, - Internal, Unknown. - :type channel: str - :param subchannel: Required. Indicates the type of modern account. Allowed values include: - Individual, Enterprise, Partner, Indirect, NotApplicable. - :type subchannel: str - :param parent: Resource ID of the parent scope. For instance, subscription's resource ID for a - resource group or a management group resource ID for a subscription. - :type parent: str - :param status: Indicates the status of the scope. Status only applies to subscriptions and - billing accounts. - :type status: str + :ivar format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType + :ivar delivery_info: Has delivery information for the export. Required. + :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :ivar definition: Has the definition for the export. Required. + :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar run_history: If requested, has the most recent execution history for the export. + :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a + blob directory together with a manifest file. Note: this option is currently available only for + modern commerce scopes. + :vartype partition_data: bool + :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the + next execution time. + :vartype next_run_time_estimate: ~datetime.datetime """ _validation = { - 'id': {'required': True}, - 'name': {'required': True}, - 'channel': {'required': True}, - 'subchannel': {'required': True}, + "delivery_info": {"required": True}, + "definition": {"required": True}, + "next_run_time_estimate": {"readonly": True}, + } + + _attribute_map = { + "format": {"key": "format", "type": "str"}, + "delivery_info": {"key": "deliveryInfo", "type": "ExportDeliveryInfo"}, + "definition": {"key": "definition", "type": "ExportDefinition"}, + "run_history": {"key": "runHistory", "type": "ExportExecutionListResult"}, + "partition_data": {"key": "partitionData", "type": "bool"}, + "next_run_time_estimate": {"key": "nextRunTimeEstimate", "type": "iso-8601"}, } + def __init__( + self, + *, + delivery_info: "_models.ExportDeliveryInfo", + definition: "_models.ExportDefinition", + format: Optional[Union[str, "_models.FormatType"]] = None, + run_history: Optional["_models.ExportExecutionListResult"] = None, + partition_data: Optional[bool] = None, + **kwargs + ): + """ + :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType + :keyword delivery_info: Has delivery information for the export. Required. + :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :keyword definition: Has the definition for the export. Required. + :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :keyword run_history: If requested, has the most recent execution history for the export. + :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :keyword partition_data: If set to true, exported data will be partitioned by size and placed + in a blob directory together with a manifest file. Note: this option is currently available + only for modern commerce scopes. + :paramtype partition_data: bool + """ + super().__init__(**kwargs) + self.format = format + self.delivery_info = delivery_info + self.definition = definition + self.run_history = run_history + self.partition_data = partition_data + self.next_run_time_estimate = None + + +class CostDetailsOperationResults(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The result of the long running operation for cost details Api. + + :ivar id: The id of the long running operation. + :vartype id: str + :ivar name: The name of the long running operation. + :vartype name: str + :ivar type: The type of the long running operation. + :vartype type: str + :ivar status: The status of the cost details operation. Known values are: "Completed", + "NoDataFound", and "Failed". + :vartype status: str or ~azure.mgmt.costmanagement.models.CostDetailsStatusType + :ivar valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype valid_till: ~datetime.datetime + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :ivar manifest_version: The Manifest version. + :vartype manifest_version: str + :ivar data_format: The data format of the report. "Csv" + :vartype data_format: str or ~azure.mgmt.costmanagement.models.CostDetailsDataFormat + :ivar byte_count: The total number of bytes in all blobs. + :vartype byte_count: int + :ivar blob_count: The total number of blobs. + :vartype blob_count: int + :ivar compress_data: Is the data in compressed format. + :vartype compress_data: bool + :ivar blobs: List of blob information generated by this operation. + :vartype blobs: list[~azure.mgmt.costmanagement.models.BlobInfo] + :ivar request_scope: The request scope of the request. + :vartype request_scope: str + :ivar request_body: The request payload body provided in Cost Details call. + :vartype request_body: + ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + """ + _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'channel': {'key': 'channel', 'type': 'str'}, - 'subchannel': {'key': 'subchannel', 'type': 'str'}, - 'parent': {'key': 'parent', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "valid_till": {"key": "validTill", "type": "iso-8601"}, + "error": {"key": "error", "type": "ErrorDetails"}, + "manifest_version": {"key": "manifest.manifestVersion", "type": "str"}, + "data_format": {"key": "manifest.dataFormat", "type": "str"}, + "byte_count": {"key": "manifest.byteCount", "type": "int"}, + "blob_count": {"key": "manifest.blobCount", "type": "int"}, + "compress_data": {"key": "manifest.compressData", "type": "bool"}, + "blobs": {"key": "manifest.blobs", "type": "[BlobInfo]"}, + "request_scope": {"key": "manifest.requestContext.requestScope", "type": "str"}, + "request_body": { + "key": "manifest.requestContext.requestBody", + "type": "GenerateCostDetailsReportRequestDefinition", + }, } def __init__( self, *, - id: str, - name: str, - channel: str, - subchannel: str, - parent: Optional[str] = None, - status: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + type: Optional[str] = None, + status: Optional[Union[str, "_models.CostDetailsStatusType"]] = None, + valid_till: Optional[datetime.datetime] = None, + error: Optional["_models.ErrorDetails"] = None, + manifest_version: Optional[str] = None, + data_format: Optional[Union[str, "_models.CostDetailsDataFormat"]] = None, + byte_count: Optional[int] = None, + blob_count: Optional[int] = None, + compress_data: Optional[bool] = None, + blobs: Optional[List["_models.BlobInfo"]] = None, + request_scope: Optional[str] = None, + request_body: Optional["_models.GenerateCostDetailsReportRequestDefinition"] = None, **kwargs ): - super(CacheItem, self).__init__(**kwargs) + """ + :keyword id: The id of the long running operation. + :paramtype id: str + :keyword name: The name of the long running operation. + :paramtype name: str + :keyword type: The type of the long running operation. + :paramtype type: str + :keyword status: The status of the cost details operation. Known values are: "Completed", + "NoDataFound", and "Failed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.CostDetailsStatusType + :keyword valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :paramtype valid_till: ~datetime.datetime + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :keyword manifest_version: The Manifest version. + :paramtype manifest_version: str + :keyword data_format: The data format of the report. "Csv" + :paramtype data_format: str or ~azure.mgmt.costmanagement.models.CostDetailsDataFormat + :keyword byte_count: The total number of bytes in all blobs. + :paramtype byte_count: int + :keyword blob_count: The total number of blobs. + :paramtype blob_count: int + :keyword compress_data: Is the data in compressed format. + :paramtype compress_data: bool + :keyword blobs: List of blob information generated by this operation. + :paramtype blobs: list[~azure.mgmt.costmanagement.models.BlobInfo] + :keyword request_scope: The request scope of the request. + :paramtype request_scope: str + :keyword request_body: The request payload body provided in Cost Details call. + :paramtype request_body: + ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + """ + super().__init__(**kwargs) self.id = id self.name = name - self.channel = channel - self.subchannel = subchannel - self.parent = parent + self.type = type self.status = status + self.valid_till = valid_till + self.error = error + self.manifest_version = manifest_version + self.data_format = data_format + self.byte_count = byte_count + self.blob_count = blob_count + self.compress_data = compress_data + self.blobs = blobs + self.request_scope = request_scope + self.request_body = request_body -class CommonExportProperties(msrest.serialization.Model): - """The common properties of the export. +class CostDetailsTimePeriod(_serialization.Model): + """The start and end date for pulling data for the cost detailed report. API only allows data to be pulled for 1 month or less and no older than 13 months. All required parameters must be populated in order to send to Azure. - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar start: The start date to pull data from. example format 2020-03-15. Required. + :vartype start: str + :ivar end: The end date to pull data to. example format 2020-03-15. Required. + :vartype end: str """ _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, + "start": {"required": True}, + "end": {"required": True}, } _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, + "start": {"key": "start", "type": "str"}, + "end": {"key": "end", "type": "str"}, } - def __init__( - self, - *, - delivery_info: "ExportDeliveryInfo", - definition: "ExportDefinition", - format: Optional[Union[str, "FormatType"]] = None, - **kwargs - ): - super(CommonExportProperties, self).__init__(**kwargs) - self.format = format - self.delivery_info = delivery_info - self.definition = definition + def __init__(self, *, start: str, end: str, **kwargs): + """ + :keyword start: The start date to pull data from. example format 2020-03-15. Required. + :paramtype start: str + :keyword end: The end date to pull data to. example format 2020-03-15. Required. + :paramtype end: str + """ + super().__init__(**kwargs) + self.start = start + self.end = end + + +class Resource(_serialization.Model): + """The Resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Location of the resource. + :vartype location: str + :ivar sku: SKU of the resource. + :vartype sku: str + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = None + self.sku = None + self.e_tag = None + self.tags = None -class Dimension(Resource): - """Dimension. +class Dimension(Resource): # pylint: disable=too-many-instance-attributes + """List of Dimension. Variables are only populated by the server, and will be ignored when sending a request. @@ -421,7 +764,13 @@ class Dimension(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar location: Location of the resource. + :vartype location: str + :ivar sku: SKU of the resource. + :vartype sku: str + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar description: Dimension description. :vartype description: str @@ -429,8 +778,8 @@ class Dimension(Resource): :vartype filter_enabled: bool :ivar grouping_enabled: Grouping enabled. :vartype grouping_enabled: bool - :param data: - :type data: list[str] + :ivar data: Dimension data. + :vartype data: list[str] :ivar total: Total number of data for the dimension. :vartype total: int :ivar category: Dimension category. @@ -444,43 +793,48 @@ class Dimension(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'description': {'readonly': True}, - 'filter_enabled': {'readonly': True}, - 'grouping_enabled': {'readonly': True}, - 'total': {'readonly': True}, - 'category': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'filter_enabled': {'key': 'properties.filterEnabled', 'type': 'bool'}, - 'grouping_enabled': {'key': 'properties.groupingEnabled', 'type': 'bool'}, - 'data': {'key': 'properties.data', 'type': '[str]'}, - 'total': {'key': 'properties.total', 'type': 'int'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'iso-8601'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'iso-8601'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, + "description": {"readonly": True}, + "filter_enabled": {"readonly": True}, + "grouping_enabled": {"readonly": True}, + "total": {"readonly": True}, + "category": {"readonly": True}, + "usage_start": {"readonly": True}, + "usage_end": {"readonly": True}, + "next_link": {"readonly": True}, } - def __init__( - self, - *, - data: Optional[List[str]] = None, - **kwargs - ): - super(Dimension, self).__init__(**kwargs) + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "description": {"key": "properties.description", "type": "str"}, + "filter_enabled": {"key": "properties.filterEnabled", "type": "bool"}, + "grouping_enabled": {"key": "properties.groupingEnabled", "type": "bool"}, + "data": {"key": "properties.data", "type": "[str]"}, + "total": {"key": "properties.total", "type": "int"}, + "category": {"key": "properties.category", "type": "str"}, + "usage_start": {"key": "properties.usageStart", "type": "iso-8601"}, + "usage_end": {"key": "properties.usageEnd", "type": "iso-8601"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + } + + def __init__(self, *, data: Optional[List[str]] = None, **kwargs): + """ + :keyword data: Dimension data. + :paramtype data: list[str] + """ + super().__init__(**kwargs) self.description = None self.filter_enabled = None self.grouping_enabled = None @@ -492,7 +846,7 @@ def __init__( self.next_link = None -class DimensionsListResult(msrest.serialization.Model): +class DimensionsListResult(_serialization.Model): """Result of listing dimensions. It contains a list of available dimensions. Variables are only populated by the server, and will be ignored when sending a request. @@ -502,72 +856,70 @@ class DimensionsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, + "value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Dimension]'}, + "value": {"key": "value", "type": "[Dimension]"}, } - def __init__( - self, - **kwargs - ): - super(DimensionsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None -class DismissAlertPayload(msrest.serialization.Model): +class DismissAlertPayload(_serialization.Model): # pylint: disable=too-many-instance-attributes """The request payload to update an alert. - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str - """ - - _attribute_map = { - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, + :ivar definition: defines the type of alert. + :vartype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :ivar description: Alert description. + :vartype description: str + :ivar source: Source of alert. Known values are: "Preset" and "User". + :vartype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :ivar details: Alert details. + :vartype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :ivar cost_entity_id: related budget. + :vartype cost_entity_id: str + :ivar status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", and + "Dismissed". + :vartype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :ivar creation_time: dateTime in which alert was created. + :vartype creation_time: str + :ivar close_time: dateTime in which alert was closed. + :vartype close_time: str + :ivar modification_time: dateTime in which alert was last modified. + :vartype modification_time: str + :ivar status_modification_user_name: User who last modified the alert. + :vartype status_modification_user_name: str + :ivar status_modification_time: dateTime in which the alert status was last modified. + :vartype status_modification_time: str + """ + + _attribute_map = { + "definition": {"key": "properties.definition", "type": "AlertPropertiesDefinition"}, + "description": {"key": "properties.description", "type": "str"}, + "source": {"key": "properties.source", "type": "str"}, + "details": {"key": "properties.details", "type": "AlertPropertiesDetails"}, + "cost_entity_id": {"key": "properties.costEntityId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "creation_time": {"key": "properties.creationTime", "type": "str"}, + "close_time": {"key": "properties.closeTime", "type": "str"}, + "modification_time": {"key": "properties.modificationTime", "type": "str"}, + "status_modification_user_name": {"key": "properties.statusModificationUserName", "type": "str"}, + "status_modification_time": {"key": "properties.statusModificationTime", "type": "str"}, } def __init__( self, *, - definition: Optional["AlertPropertiesDefinition"] = None, + definition: Optional["_models.AlertPropertiesDefinition"] = None, description: Optional[str] = None, - source: Optional[Union[str, "AlertSource"]] = None, - details: Optional["AlertPropertiesDetails"] = None, + source: Optional[Union[str, "_models.AlertSource"]] = None, + details: Optional["_models.AlertPropertiesDetails"] = None, cost_entity_id: Optional[str] = None, - status: Optional[Union[str, "AlertStatus"]] = None, + status: Optional[Union[str, "_models.AlertStatus"]] = None, creation_time: Optional[str] = None, close_time: Optional[str] = None, modification_time: Optional[str] = None, @@ -575,7 +927,32 @@ def __init__( status_modification_time: Optional[str] = None, **kwargs ): - super(DismissAlertPayload, self).__init__(**kwargs) + """ + :keyword definition: defines the type of alert. + :paramtype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :keyword description: Alert description. + :paramtype description: str + :keyword source: Source of alert. Known values are: "Preset" and "User". + :paramtype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :keyword details: Alert details. + :paramtype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :keyword cost_entity_id: related budget. + :paramtype cost_entity_id: str + :keyword status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", + and "Dismissed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :keyword creation_time: dateTime in which alert was created. + :paramtype creation_time: str + :keyword close_time: dateTime in which alert was closed. + :paramtype close_time: str + :keyword modification_time: dateTime in which alert was last modified. + :paramtype modification_time: str + :keyword status_modification_user_name: User who last modified the alert. + :paramtype status_modification_user_name: str + :keyword status_modification_time: dateTime in which the alert status was last modified. + :paramtype status_modification_time: str + """ + super().__init__(**kwargs) self.definition = definition self.description = description self.source = source @@ -589,7 +966,7 @@ def __init__( self.status_modification_time = status_modification_time -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. @@ -601,56 +978,53 @@ class ErrorDetails(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(ErrorDetails, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None -class ErrorResponse(msrest.serialization.Model): - """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. +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. -Some Error responses: + Some Error responses: -* - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. + * + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. -* - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + * + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. - :param error: The details of the error. - :type error: ~azure.mgmt.costmanagement.models.ErrorDetails + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, + "error": {"key": "error", "type": "ErrorDetails"}, } - def __init__( - self, - *, - error: Optional["ErrorDetails"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(**kwargs) self.error = error -class ProxyResource(msrest.serialization.Model): - """The Resource model definition. +class Export(ProxyResource): # pylint: disable=too-many-instance-attributes + """An export resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -660,209 +1034,312 @@ class ProxyResource(msrest.serialization.Model): :vartype name: str :ivar type: Resource type. :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. - :type e_tag: str + :vartype e_tag: str + :ivar format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType + :ivar delivery_info: Has delivery information for the export. + :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :ivar definition: Has the definition for the export. + :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar run_history: If requested, has the most recent execution history for the export. + :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a + blob directory together with a manifest file. Note: this option is currently available only for + modern commerce scopes. + :vartype partition_data: bool + :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the + next execution time. + :vartype next_run_time_estimate: ~datetime.datetime + :ivar schedule: Has schedule information for the export. + :vartype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "next_run_time_estimate": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "format": {"key": "properties.format", "type": "str"}, + "delivery_info": {"key": "properties.deliveryInfo", "type": "ExportDeliveryInfo"}, + "definition": {"key": "properties.definition", "type": "ExportDefinition"}, + "run_history": {"key": "properties.runHistory", "type": "ExportExecutionListResult"}, + "partition_data": {"key": "properties.partitionData", "type": "bool"}, + "next_run_time_estimate": {"key": "properties.nextRunTimeEstimate", "type": "iso-8601"}, + "schedule": {"key": "properties.schedule", "type": "ExportSchedule"}, } def __init__( self, *, e_tag: Optional[str] = None, + format: Optional[Union[str, "_models.FormatType"]] = None, + delivery_info: Optional["_models.ExportDeliveryInfo"] = None, + definition: Optional["_models.ExportDefinition"] = None, + run_history: Optional["_models.ExportExecutionListResult"] = None, + partition_data: Optional[bool] = None, + schedule: Optional["_models.ExportSchedule"] = None, **kwargs ): - super(ProxyResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.e_tag = e_tag - + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType + :keyword delivery_info: Has delivery information for the export. + :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :keyword definition: Has the definition for the export. + :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :keyword run_history: If requested, has the most recent execution history for the export. + :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :keyword partition_data: If set to true, exported data will be partitioned by size and placed + in a blob directory together with a manifest file. Note: this option is currently available + only for modern commerce scopes. + :paramtype partition_data: bool + :keyword schedule: Has schedule information for the export. + :paramtype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + """ + super().__init__(e_tag=e_tag, **kwargs) + self.format = format + self.delivery_info = delivery_info + self.definition = definition + self.run_history = run_history + self.partition_data = partition_data + self.next_run_time_estimate = None + self.schedule = schedule -class Export(ProxyResource): - """A export resource. - Variables are only populated by the server, and will be ignored when sending a request. +class ExportDataset(_serialization.Model): + """The definition for data in the export. - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + :ivar granularity: The granularity of rows in the export. Currently only 'Daily' is supported. + "Daily" + :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :ivar configuration: The export dataset configuration. + :vartype configuration: ~azure.mgmt.costmanagement.models.ExportDatasetConfiguration """ - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'format': {'key': 'properties.format', 'type': 'str'}, - 'delivery_info': {'key': 'properties.deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'properties.definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'properties.schedule', 'type': 'ExportSchedule'}, + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "ExportDatasetConfiguration"}, } def __init__( self, *, - e_tag: Optional[str] = None, - format: Optional[Union[str, "FormatType"]] = None, - delivery_info: Optional["ExportDeliveryInfo"] = None, - definition: Optional["ExportDefinition"] = None, - schedule: Optional["ExportSchedule"] = None, + granularity: Optional[Union[str, "_models.GranularityType"]] = None, + configuration: Optional["_models.ExportDatasetConfiguration"] = None, **kwargs ): - super(Export, self).__init__(e_tag=e_tag, **kwargs) - self.format = format - self.delivery_info = delivery_info - self.definition = definition - self.schedule = schedule + """ + :keyword granularity: The granularity of rows in the export. Currently only 'Daily' is + supported. "Daily" + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :keyword configuration: The export dataset configuration. + :paramtype configuration: ~azure.mgmt.costmanagement.models.ExportDatasetConfiguration + """ + super().__init__(**kwargs) + self.granularity = granularity + self.configuration = configuration -class ExportDefinition(msrest.serialization.Model): - """The definition of a query. +class ExportDatasetConfiguration(_serialization.Model): + """The export dataset configuration. Allows columns to be selected for the export. If not provided then the export will include all available columns. + + :ivar columns: Array of column names to be included in the export. If not provided then the + export will include all available columns. The available columns can vary by customer channel + (see examples). + :vartype columns: list[str] + """ + + _attribute_map = { + "columns": {"key": "columns", "type": "[str]"}, + } + + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the export. If not provided then the + export will include all available columns. The available columns can vary by customer channel + (see examples). + :paramtype columns: list[str] + """ + super().__init__(**kwargs) + self.columns = columns + + +class ExportDefinition(_serialization.Model): + """The definition of an export. All required parameters must be populated in order to send to Azure. - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", - "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param data_set: Has definition for data in this query. - :type data_set: ~azure.mgmt.costmanagement.models.QueryDatasetAutoGenerated + :ivar type: The type of the export. Note that 'Usage' is equivalent to 'ActualCost' and is + applicable to exports that do not yet provide data for charges or amortization for service + reservations. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". + :vartype type: str or ~azure.mgmt.costmanagement.models.ExportType + :ivar timeframe: The time frame for pulling data for the export. If custom, then a specific + time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :ivar time_period: Has time period for pulling data for the export. + :vartype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod + :ivar data_set: The definition for data in the export. + :vartype data_set: ~azure.mgmt.costmanagement.models.ExportDataset """ _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, + "type": {"required": True}, + "timeframe": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'data_set': {'key': 'dataSet', 'type': 'QueryDatasetAutoGenerated'}, + "type": {"key": "type", "type": "str"}, + "timeframe": {"key": "timeframe", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "ExportTimePeriod"}, + "data_set": {"key": "dataSet", "type": "ExportDataset"}, } def __init__( self, *, - type: Union[str, "ExportType"], - timeframe: Union[str, "TimeframeType"], - time_period: Optional["QueryTimePeriod"] = None, - data_set: Optional["QueryDatasetAutoGenerated"] = None, + type: Union[str, "_models.ExportType"], + timeframe: Union[str, "_models.TimeframeType"], + time_period: Optional["_models.ExportTimePeriod"] = None, + data_set: Optional["_models.ExportDataset"] = None, **kwargs ): - super(ExportDefinition, self).__init__(**kwargs) + """ + :keyword type: The type of the export. Note that 'Usage' is equivalent to 'ActualCost' and is + applicable to exports that do not yet provide data for charges or amortization for service + reservations. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ExportType + :keyword timeframe: The time frame for pulling data for the export. If custom, then a specific + time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :keyword time_period: Has time period for pulling data for the export. + :paramtype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod + :keyword data_set: The definition for data in the export. + :paramtype data_set: ~azure.mgmt.costmanagement.models.ExportDataset + """ + super().__init__(**kwargs) self.type = type self.timeframe = timeframe self.time_period = time_period self.data_set = data_set -class ExportDeliveryDestination(msrest.serialization.Model): - """The destination information for the delivery of the export. To allow access to a storage account, you must register the account's subscription with the Microsoft.CostManagementExports resource provider. This is required once per subscription. When creating an export in the Azure portal, it is done automatically, however API users need to register the subscription. For more information see https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services . +class ExportDeliveryDestination(_serialization.Model): + """This represents the blob storage account location where exports of costs will be delivered. There are two ways to configure the destination. The approach recommended for most customers is to specify the resourceId of the storage account. This requires a one-time registration of the account's subscription with the Microsoft.CostManagementExports resource provider in order to give Cost Management services access to the storage. When creating an export in the Azure portal this registration is performed automatically but API users may need to register the subscription explicitly (for more information see https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services ). Another way to configure the destination is available ONLY to Partners with a Microsoft Partner Agreement plan who are global admins of their billing account. These Partners, instead of specifying the resourceId of a storage account, can specify the storage account name along with a SAS token for the account. This allows exports of costs to a storage account in any tenant. The SAS token should be created for the blob service with Service/Container/Object resource types and with Read/Write/Delete/List/Add/Create permissions (for more information see https://docs.microsoft.com/en-us/azure/cost-management-billing/costs/export-cost-data-storage-account-sas-key ). All required parameters must be populated in order to send to Azure. - :param resource_id: Required. The resource id of the storage account where exports will be - delivered. - :type resource_id: str - :param container: Required. The name of the container where exports will be uploaded. - :type container: str - :param root_folder_path: The name of the directory where exports will be uploaded. - :type root_folder_path: str + :ivar resource_id: The resource id of the storage account where exports will be delivered. This + is not required if a sasToken and storageAccount are specified. + :vartype resource_id: str + :ivar container: The name of the container where exports will be uploaded. If the container + does not exist it will be created. Required. + :vartype container: str + :ivar root_folder_path: The name of the directory where exports will be uploaded. + :vartype root_folder_path: str + :ivar sas_token: A SAS token for the storage account. For a restricted set of Azure customers + this together with storageAccount can be specified instead of resourceId. Note: the value + returned by the API for this property will always be obfuscated. Returning this same obfuscated + value will not result in the SAS token being updated. To update this value a new SAS token must + be specified. + :vartype sas_token: str + :ivar storage_account: The storage account where exports will be uploaded. For a restricted set + of Azure customers this together with sasToken can be specified instead of resourceId. + :vartype storage_account: str """ _validation = { - 'resource_id': {'required': True}, - 'container': {'required': True}, + "container": {"required": True}, } _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'container': {'key': 'container', 'type': 'str'}, - 'root_folder_path': {'key': 'rootFolderPath', 'type': 'str'}, + "resource_id": {"key": "resourceId", "type": "str"}, + "container": {"key": "container", "type": "str"}, + "root_folder_path": {"key": "rootFolderPath", "type": "str"}, + "sas_token": {"key": "sasToken", "type": "str"}, + "storage_account": {"key": "storageAccount", "type": "str"}, } def __init__( self, *, - resource_id: str, container: str, + resource_id: Optional[str] = None, root_folder_path: Optional[str] = None, + sas_token: Optional[str] = None, + storage_account: Optional[str] = None, **kwargs ): - super(ExportDeliveryDestination, self).__init__(**kwargs) + """ + :keyword resource_id: The resource id of the storage account where exports will be delivered. + This is not required if a sasToken and storageAccount are specified. + :paramtype resource_id: str + :keyword container: The name of the container where exports will be uploaded. If the container + does not exist it will be created. Required. + :paramtype container: str + :keyword root_folder_path: The name of the directory where exports will be uploaded. + :paramtype root_folder_path: str + :keyword sas_token: A SAS token for the storage account. For a restricted set of Azure + customers this together with storageAccount can be specified instead of resourceId. Note: the + value returned by the API for this property will always be obfuscated. Returning this same + obfuscated value will not result in the SAS token being updated. To update this value a new SAS + token must be specified. + :paramtype sas_token: str + :keyword storage_account: The storage account where exports will be uploaded. For a restricted + set of Azure customers this together with sasToken can be specified instead of resourceId. + :paramtype storage_account: str + """ + super().__init__(**kwargs) self.resource_id = resource_id self.container = container self.root_folder_path = root_folder_path + self.sas_token = sas_token + self.storage_account = storage_account -class ExportDeliveryInfo(msrest.serialization.Model): +class ExportDeliveryInfo(_serialization.Model): """The delivery information associated with a export. All required parameters must be populated in order to send to Azure. - :param destination: Required. Has destination for the export being delivered. - :type destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination + :ivar destination: Has destination for the export being delivered. Required. + :vartype destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination """ _validation = { - 'destination': {'required': True}, + "destination": {"required": True}, } _attribute_map = { - 'destination': {'key': 'destination', 'type': 'ExportDeliveryDestination'}, + "destination": {"key": "destination", "type": "ExportDeliveryDestination"}, } - def __init__( - self, - *, - destination: "ExportDeliveryDestination", - **kwargs - ): - super(ExportDeliveryInfo, self).__init__(**kwargs) + def __init__(self, *, destination: "_models.ExportDeliveryDestination", **kwargs): + """ + :keyword destination: Has destination for the export being delivered. Required. + :paramtype destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination + """ + super().__init__(**kwargs) self.destination = destination -class ExportExecution(Resource): - """A export execution. +class ExportExecution(ProxyResource): # pylint: disable=too-many-instance-attributes + """An export execution. Variables are only populated by the server, and will be ignored when sending a request. @@ -872,65 +1349,96 @@ class ExportExecution(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param execution_type: The type of the export execution. Possible values include: "OnDemand", + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str + :ivar execution_type: The type of the export execution. Known values are: "OnDemand" and "Scheduled". - :type execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType - :param status: The status of the export execution. Possible values include: "Queued", - "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", "DataNotAvailable". - :type status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus - :param submitted_by: The identifier for the entity that executed the export. For OnDemand - executions, it is the email id. For Scheduled executions, it is the constant value - System. - :type submitted_by: str - :param submitted_time: The time when export was queued to be executed. - :type submitted_time: ~datetime.datetime - :param processing_start_time: The time when export was picked up to be executed. - :type processing_start_time: ~datetime.datetime - :param processing_end_time: The time when export execution finished. - :type processing_end_time: ~datetime.datetime - :param file_name: The name of the file export got written to. - :type file_name: str - :param run_settings: The common properties of the export. - :type run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties + :vartype execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType + :ivar status: The last known status of the export execution. Known values are: "Queued", + "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", and "DataNotAvailable". + :vartype status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus + :ivar submitted_by: The identifier for the entity that executed the export. For OnDemand + executions it is the user email. For scheduled executions it is 'System'. + :vartype submitted_by: str + :ivar submitted_time: The time when export was queued to be executed. + :vartype submitted_time: ~datetime.datetime + :ivar processing_start_time: The time when export was picked up to be executed. + :vartype processing_start_time: ~datetime.datetime + :ivar processing_end_time: The time when the export execution finished. + :vartype processing_end_time: ~datetime.datetime + :ivar file_name: The name of the exported file. + :vartype file_name: str + :ivar run_settings: The export settings that were in effect for this execution. + :vartype run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties + :ivar error: The details of any error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'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'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'execution_type': {'key': 'properties.executionType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'submitted_by': {'key': 'properties.submittedBy', 'type': 'str'}, - 'submitted_time': {'key': 'properties.submittedTime', 'type': 'iso-8601'}, - 'processing_start_time': {'key': 'properties.processingStartTime', 'type': 'iso-8601'}, - 'processing_end_time': {'key': 'properties.processingEndTime', 'type': 'iso-8601'}, - 'file_name': {'key': 'properties.fileName', 'type': 'str'}, - 'run_settings': {'key': 'properties.runSettings', 'type': 'CommonExportProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "execution_type": {"key": "properties.executionType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "submitted_by": {"key": "properties.submittedBy", "type": "str"}, + "submitted_time": {"key": "properties.submittedTime", "type": "iso-8601"}, + "processing_start_time": {"key": "properties.processingStartTime", "type": "iso-8601"}, + "processing_end_time": {"key": "properties.processingEndTime", "type": "iso-8601"}, + "file_name": {"key": "properties.fileName", "type": "str"}, + "run_settings": {"key": "properties.runSettings", "type": "CommonExportProperties"}, + "error": {"key": "properties.error", "type": "ErrorDetails"}, } def __init__( self, *, - execution_type: Optional[Union[str, "ExecutionType"]] = None, - status: Optional[Union[str, "ExecutionStatus"]] = None, + e_tag: Optional[str] = None, + execution_type: Optional[Union[str, "_models.ExecutionType"]] = None, + status: Optional[Union[str, "_models.ExecutionStatus"]] = None, submitted_by: Optional[str] = None, submitted_time: Optional[datetime.datetime] = None, processing_start_time: Optional[datetime.datetime] = None, processing_end_time: Optional[datetime.datetime] = None, file_name: Optional[str] = None, - run_settings: Optional["CommonExportProperties"] = None, + run_settings: Optional["_models.CommonExportProperties"] = None, + error: Optional["_models.ErrorDetails"] = None, **kwargs ): - super(ExportExecution, self).__init__(**kwargs) + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword execution_type: The type of the export execution. Known values are: "OnDemand" and + "Scheduled". + :paramtype execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType + :keyword status: The last known status of the export execution. Known values are: "Queued", + "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", and "DataNotAvailable". + :paramtype status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus + :keyword submitted_by: The identifier for the entity that executed the export. For OnDemand + executions it is the user email. For scheduled executions it is 'System'. + :paramtype submitted_by: str + :keyword submitted_time: The time when export was queued to be executed. + :paramtype submitted_time: ~datetime.datetime + :keyword processing_start_time: The time when export was picked up to be executed. + :paramtype processing_start_time: ~datetime.datetime + :keyword processing_end_time: The time when the export execution finished. + :paramtype processing_end_time: ~datetime.datetime + :keyword file_name: The name of the exported file. + :paramtype file_name: str + :keyword run_settings: The export settings that were in effect for this execution. + :paramtype run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties + :keyword error: The details of any error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(e_tag=e_tag, **kwargs) self.execution_type = execution_type self.status = status self.submitted_by = submitted_by @@ -939,34 +1447,33 @@ def __init__( self.processing_end_time = processing_end_time self.file_name = file_name self.run_settings = run_settings + self.error = error -class ExportExecutionListResult(msrest.serialization.Model): - """Result of listing exports execution history of a export by name. +class ExportExecutionListResult(_serialization.Model): + """Result of listing the execution history of an export. Variables are only populated by the server, and will be ignored when sending a request. - :ivar value: The list of export executions. + :ivar value: A list of export executions. :vartype value: list[~azure.mgmt.costmanagement.models.ExportExecution] """ _validation = { - 'value': {'readonly': True}, + "value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ExportExecution]'}, + "value": {"key": "value", "type": "[ExportExecution]"}, } - def __init__( - self, - **kwargs - ): - super(ExportExecutionListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None -class ExportListResult(msrest.serialization.Model): +class ExportListResult(_serialization.Model): """Result of listing exports. It contains a list of available exports in the scope provided. Variables are only populated by the server, and will be ignored when sending a request. @@ -976,377 +1483,520 @@ class ExportListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, + "value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Export]'}, + "value": {"key": "value", "type": "[Export]"}, } - def __init__( - self, - **kwargs - ): - super(ExportListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None class ExportProperties(CommonExportProperties): """The properties of the export. + Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to Azure. - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + :ivar format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType + :ivar delivery_info: Has delivery information for the export. Required. + :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :ivar definition: Has the definition for the export. Required. + :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar run_history: If requested, has the most recent execution history for the export. + :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a + blob directory together with a manifest file. Note: this option is currently available only for + modern commerce scopes. + :vartype partition_data: bool + :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the + next execution time. + :vartype next_run_time_estimate: ~datetime.datetime + :ivar schedule: Has schedule information for the export. + :vartype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule """ _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, + "delivery_info": {"required": True}, + "definition": {"required": True}, + "next_run_time_estimate": {"readonly": True}, } _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'schedule', 'type': 'ExportSchedule'}, + "format": {"key": "format", "type": "str"}, + "delivery_info": {"key": "deliveryInfo", "type": "ExportDeliveryInfo"}, + "definition": {"key": "definition", "type": "ExportDefinition"}, + "run_history": {"key": "runHistory", "type": "ExportExecutionListResult"}, + "partition_data": {"key": "partitionData", "type": "bool"}, + "next_run_time_estimate": {"key": "nextRunTimeEstimate", "type": "iso-8601"}, + "schedule": {"key": "schedule", "type": "ExportSchedule"}, } def __init__( self, *, - delivery_info: "ExportDeliveryInfo", - definition: "ExportDefinition", - format: Optional[Union[str, "FormatType"]] = None, - schedule: Optional["ExportSchedule"] = None, + delivery_info: "_models.ExportDeliveryInfo", + definition: "_models.ExportDefinition", + format: Optional[Union[str, "_models.FormatType"]] = None, + run_history: Optional["_models.ExportExecutionListResult"] = None, + partition_data: Optional[bool] = None, + schedule: Optional["_models.ExportSchedule"] = None, **kwargs ): - super(ExportProperties, self).__init__(format=format, delivery_info=delivery_info, definition=definition, **kwargs) + """ + :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType + :keyword delivery_info: Has delivery information for the export. Required. + :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :keyword definition: Has the definition for the export. Required. + :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :keyword run_history: If requested, has the most recent execution history for the export. + :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :keyword partition_data: If set to true, exported data will be partitioned by size and placed + in a blob directory together with a manifest file. Note: this option is currently available + only for modern commerce scopes. + :paramtype partition_data: bool + :keyword schedule: Has schedule information for the export. + :paramtype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + """ + super().__init__( + format=format, + delivery_info=delivery_info, + definition=definition, + run_history=run_history, + partition_data=partition_data, + **kwargs + ) self.schedule = schedule -class ExportRecurrencePeriod(msrest.serialization.Model): +class ExportRecurrencePeriod(_serialization.Model): """The start and end date for recurrence schedule. All required parameters must be populated in order to send to Azure. - :param from_property: Required. The start date of recurrence. - :type from_property: ~datetime.datetime - :param to: The end date of recurrence. - :type to: ~datetime.datetime + :ivar from_property: The start date of recurrence. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date of recurrence. + :vartype to: ~datetime.datetime """ _validation = { - 'from_property': {'required': True}, + "from_property": {"required": True}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - *, - from_property: datetime.datetime, - to: Optional[datetime.datetime] = None, - **kwargs - ): - super(ExportRecurrencePeriod, self).__init__(**kwargs) + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, + } + + def __init__(self, *, from_property: datetime.datetime, to: Optional[datetime.datetime] = None, **kwargs): + """ + :keyword from_property: The start date of recurrence. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date of recurrence. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) self.from_property = from_property self.to = to -class ExportSchedule(msrest.serialization.Model): - """The schedule associated with a export. +class ExportSchedule(_serialization.Model): + """The schedule associated with the export. - All required parameters must be populated in order to send to Azure. - - :param status: The status of the schedule. Whether active or not. If inactive, the export's - scheduled execution is paused. Possible values include: "Active", "Inactive". - :type status: str or ~azure.mgmt.costmanagement.models.StatusType - :param recurrence: Required. The schedule recurrence. Possible values include: "Daily", - "Weekly", "Monthly", "Annually". - :type recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType - :param recurrence_period: Has start and end date of the recurrence. The start date must be in + :ivar status: The status of the export's schedule. If 'Inactive', the export's schedule is + paused. Known values are: "Active" and "Inactive". + :vartype status: str or ~azure.mgmt.costmanagement.models.StatusType + :ivar recurrence: The schedule recurrence. Known values are: "Daily", "Weekly", "Monthly", and + "Annually". + :vartype recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType + :ivar recurrence_period: Has start and end date of the recurrence. The start date must be in future. If present, the end date must be greater than start date. - :type recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod + :vartype recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod """ - _validation = { - 'recurrence': {'required': True}, - } - _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'recurrence': {'key': 'recurrence', 'type': 'str'}, - 'recurrence_period': {'key': 'recurrencePeriod', 'type': 'ExportRecurrencePeriod'}, + "status": {"key": "status", "type": "str"}, + "recurrence": {"key": "recurrence", "type": "str"}, + "recurrence_period": {"key": "recurrencePeriod", "type": "ExportRecurrencePeriod"}, } def __init__( self, *, - recurrence: Union[str, "RecurrenceType"], - status: Optional[Union[str, "StatusType"]] = None, - recurrence_period: Optional["ExportRecurrencePeriod"] = None, + status: Optional[Union[str, "_models.StatusType"]] = None, + recurrence: Optional[Union[str, "_models.RecurrenceType"]] = None, + recurrence_period: Optional["_models.ExportRecurrencePeriod"] = None, **kwargs ): - super(ExportSchedule, self).__init__(**kwargs) + """ + :keyword status: The status of the export's schedule. If 'Inactive', the export's schedule is + paused. Known values are: "Active" and "Inactive". + :paramtype status: str or ~azure.mgmt.costmanagement.models.StatusType + :keyword recurrence: The schedule recurrence. Known values are: "Daily", "Weekly", "Monthly", + and "Annually". + :paramtype recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType + :keyword recurrence_period: Has start and end date of the recurrence. The start date must be in + future. If present, the end date must be greater than start date. + :paramtype recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod + """ + super().__init__(**kwargs) self.status = status self.recurrence = recurrence self.recurrence_period = recurrence_period -class ForecastDefinition(msrest.serialization.Model): - """The definition of a forecast. +class ExportTimePeriod(_serialization.Model): + """The date range for data in the export. This should only be specified with timeFrame set to 'Custom'. The maximum date range is 3 months. All required parameters must be populated in order to send to Azure. - :param type: Required. The type of the forecast. Possible values include: "Usage", - "ActualCost", "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ForecastType - :param timeframe: Required. The time frame for pulling data for the forecast. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframeType - :param time_period: Has time period for pulling data for the forecast. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this forecast. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset - :param include_actual_cost: a boolean determining if actualCost will be included. - :type include_actual_cost: bool - :param include_fresh_partial_cost: a boolean determining if FreshPartialCost will be included. - :type include_fresh_partial_cost: bool + :ivar from_property: The start date for export data. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date for export data. Required. + :vartype to: ~datetime.datetime """ _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, + "from_property": {"required": True}, + "to": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, - 'include_actual_cost': {'key': 'includeActualCost', 'type': 'bool'}, - 'include_fresh_partial_cost': {'key': 'includeFreshPartialCost', 'type': 'bool'}, - } + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, + } + + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date for export data. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date for export data. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) + self.from_property = from_property + self.to = to - def __init__( - self, - *, - type: Union[str, "ForecastType"], - timeframe: Union[str, "ForecastTimeframeType"], - dataset: "QueryDataset", - time_period: Optional["QueryTimePeriod"] = None, - include_actual_cost: Optional[bool] = None, - include_fresh_partial_cost: Optional[bool] = None, - **kwargs - ): - super(ForecastDefinition, self).__init__(**kwargs) - self.type = type - self.timeframe = timeframe - self.time_period = time_period - self.dataset = dataset - self.include_actual_cost = include_actual_cost - self.include_fresh_partial_cost = include_fresh_partial_cost +class ForecastAggregation(_serialization.Model): + """The aggregation expression to be used in the forecast. -class KpiProperties(msrest.serialization.Model): - """Each KPI must contain a 'type' and 'enabled' key. + All required parameters must be populated in order to send to Azure. - :param type: KPI type (Forecast, Budget). Possible values include: "Forecast", "Budget". - :type type: str or ~azure.mgmt.costmanagement.models.KpiType - :param id: ID of resource related to metric (budget). - :type id: str - :param enabled: show the KPI in the UI?. - :type enabled: bool + :ivar name: The name of the column to aggregate. Required. Known values are: "PreTaxCostUSD", + "Cost", "CostUSD", and "PreTaxCost". + :vartype name: str or ~azure.mgmt.costmanagement.models.FunctionName + :ivar function: The name of the aggregation function to use. Required. "Sum" + :vartype function: str or ~azure.mgmt.costmanagement.models.FunctionType """ + _validation = { + "name": {"required": True}, + "function": {"required": True}, + } + _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'enabled': {'key': 'enabled', 'type': 'bool'}, + "name": {"key": "name", "type": "str"}, + "function": {"key": "function", "type": "str"}, } def __init__( - self, - *, - type: Optional[Union[str, "KpiType"]] = None, - id: Optional[str] = None, - enabled: Optional[bool] = None, - **kwargs + self, *, name: Union[str, "_models.FunctionName"], function: Union[str, "_models.FunctionType"], **kwargs ): - super(KpiProperties, self).__init__(**kwargs) + """ + :keyword name: The name of the column to aggregate. Required. Known values are: + "PreTaxCostUSD", "Cost", "CostUSD", and "PreTaxCost". + :paramtype name: str or ~azure.mgmt.costmanagement.models.FunctionName + :keyword function: The name of the aggregation function to use. Required. "Sum" + :paramtype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + super().__init__(**kwargs) + self.name = name + self.function = function + + +class ForecastColumn(_serialization.Model): + """Forecast column properties. + + :ivar name: The name of column. + :vartype name: str + :ivar type: The type of column. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword name: The name of column. + :paramtype name: str + :keyword type: The type of column. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name self.type = type - self.id = id - self.enabled = enabled -class Operation(msrest.serialization.Model): - """A Cost management REST API operation. +class ForecastComparisonExpression(_serialization.Model): + """The comparison expression to be used in the forecast. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to Azure. - :ivar name: Operation name: {provider}/{resource}/{operation}. + :ivar name: The name of the column to use in comparison. Required. :vartype name: str - :param display: The object that represents the operation. - :type display: ~azure.mgmt.costmanagement.models.OperationDisplay + :ivar operator: The operator to use for comparison. Required. "In" + :vartype operator: str or ~azure.mgmt.costmanagement.models.ForecastOperatorType + :ivar values: Array of values to use for comparison. Required. + :vartype values: list[str] """ _validation = { - 'name': {'readonly': True}, + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True, "min_items": 1}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - } - - def __init__( - self, - *, - display: Optional["OperationDisplay"] = None, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = None - self.display = display + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__(self, *, name: str, operator: Union[str, "_models.ForecastOperatorType"], values: List[str], **kwargs): + """ + :keyword name: The name of the column to use in comparison. Required. + :paramtype name: str + :keyword operator: The operator to use for comparison. Required. "In" + :paramtype operator: str or ~azure.mgmt.costmanagement.models.ForecastOperatorType + :keyword values: Array of values to use for comparison. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) + self.name = name + self.operator = operator + self.values = values -class OperationDisplay(msrest.serialization.Model): - """The object that represents the operation. +class ForecastDataset(_serialization.Model): + """The definition of data present in the forecast. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to Azure. - :ivar provider: Service provider: Microsoft.CostManagement. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Dimensions, Query. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str + :ivar granularity: The granularity of rows in the forecast. "Daily" + :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :ivar configuration: Has configuration information for the data in the export. The + configuration will be ignored if aggregation and grouping are provided. + :vartype configuration: ~azure.mgmt.costmanagement.models.ForecastDatasetConfiguration + :ivar aggregation: Dictionary of aggregation expression to use in the forecast. The key of each + item in the dictionary is the alias for the aggregated column. forecast can have up to 2 + aggregation clauses. Required. + :vartype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ForecastAggregation] + :ivar filter: Has filter expression to use in the forecast. + :vartype filter: ~azure.mgmt.costmanagement.models.ForecastFilter """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, + "aggregation": {"required": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "ForecastDatasetConfiguration"}, + "aggregation": {"key": "aggregation", "type": "{ForecastAggregation}"}, + "filter": {"key": "filter", "type": "ForecastFilter"}, } def __init__( self, + *, + aggregation: Dict[str, "_models.ForecastAggregation"], + granularity: Optional[Union[str, "_models.GranularityType"]] = None, + configuration: Optional["_models.ForecastDatasetConfiguration"] = None, + filter: Optional["_models.ForecastFilter"] = None, # pylint: disable=redefined-builtin **kwargs ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None + """ + :keyword granularity: The granularity of rows in the forecast. "Daily" + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :keyword configuration: Has configuration information for the data in the export. The + configuration will be ignored if aggregation and grouping are provided. + :paramtype configuration: ~azure.mgmt.costmanagement.models.ForecastDatasetConfiguration + :keyword aggregation: Dictionary of aggregation expression to use in the forecast. The key of + each item in the dictionary is the alias for the aggregated column. forecast can have up to 2 + aggregation clauses. Required. + :paramtype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ForecastAggregation] + :keyword filter: Has filter expression to use in the forecast. + :paramtype filter: ~azure.mgmt.costmanagement.models.ForecastFilter + """ + super().__init__(**kwargs) + self.granularity = granularity + self.configuration = configuration + self.aggregation = aggregation + self.filter = filter -class OperationListResult(msrest.serialization.Model): - """Result of listing cost management operations. It contains a list of operations and a URL link to get the next set of results. +class ForecastDatasetConfiguration(_serialization.Model): + """The configuration of dataset in the forecast. - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of cost management operations supported by the Microsoft.CostManagement - resource provider. - :vartype value: list[~azure.mgmt.costmanagement.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str + :ivar columns: Array of column names to be included in the forecast. Any valid forecast column + name is allowed. If not provided, then forecast includes all columns. + :vartype columns: list[str] """ - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "columns": {"key": "columns", "type": "[str]"}, } - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the forecast. Any valid forecast + column name is allowed. If not provided, then forecast includes all columns. + :paramtype columns: list[str] + """ + super().__init__(**kwargs) + self.columns = columns -class OperationStatus(msrest.serialization.Model): - """The status of the long running operation. +class ForecastDefinition(_serialization.Model): + """The definition of a forecast. - :param status: The status of the long running operation. - :type status: ~azure.mgmt.costmanagement.models.Status - :param report_url: The URL to download the generated report. - :type report_url: str - :param valid_until: The time at which report URL becomes invalid. - :type valid_until: ~datetime.datetime + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of the forecast. Required. Known values are: "Usage", "ActualCost", and + "AmortizedCost". + :vartype type: str or ~azure.mgmt.costmanagement.models.ForecastType + :ivar timeframe: The time frame for pulling data for the forecast. If custom, then a specific + time period must be provided. Required. "Custom" + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframe + :ivar time_period: Has time period for pulling data for the forecast. + :vartype time_period: ~azure.mgmt.costmanagement.models.ForecastTimePeriod + :ivar dataset: Has definition for data in this forecast. Required. + :vartype dataset: ~azure.mgmt.costmanagement.models.ForecastDataset + :ivar include_actual_cost: A boolean determining if actualCost will be included. + :vartype include_actual_cost: bool + :ivar include_fresh_partial_cost: A boolean determining if FreshPartialCost will be included. + :vartype include_fresh_partial_cost: bool """ + _validation = { + "type": {"required": True}, + "timeframe": {"required": True}, + "dataset": {"required": True}, + } + _attribute_map = { - 'status': {'key': 'status', 'type': 'Status'}, - 'report_url': {'key': 'properties.reportUrl', 'type': 'str'}, - 'valid_until': {'key': 'properties.validUntil', 'type': 'iso-8601'}, + "type": {"key": "type", "type": "str"}, + "timeframe": {"key": "timeframe", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "ForecastTimePeriod"}, + "dataset": {"key": "dataset", "type": "ForecastDataset"}, + "include_actual_cost": {"key": "includeActualCost", "type": "bool"}, + "include_fresh_partial_cost": {"key": "includeFreshPartialCost", "type": "bool"}, } def __init__( self, *, - status: Optional["Status"] = None, - report_url: Optional[str] = None, - valid_until: Optional[datetime.datetime] = None, + type: Union[str, "_models.ForecastType"], + timeframe: Union[str, "_models.ForecastTimeframe"], + dataset: "_models.ForecastDataset", + time_period: Optional["_models.ForecastTimePeriod"] = None, + include_actual_cost: Optional[bool] = None, + include_fresh_partial_cost: Optional[bool] = None, **kwargs ): - super(OperationStatus, self).__init__(**kwargs) - self.status = status - self.report_url = report_url - self.valid_until = valid_until + """ + :keyword type: The type of the forecast. Required. Known values are: "Usage", "ActualCost", and + "AmortizedCost". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ForecastType + :keyword timeframe: The time frame for pulling data for the forecast. If custom, then a + specific time period must be provided. Required. "Custom" + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframe + :keyword time_period: Has time period for pulling data for the forecast. + :paramtype time_period: ~azure.mgmt.costmanagement.models.ForecastTimePeriod + :keyword dataset: Has definition for data in this forecast. Required. + :paramtype dataset: ~azure.mgmt.costmanagement.models.ForecastDataset + :keyword include_actual_cost: A boolean determining if actualCost will be included. + :paramtype include_actual_cost: bool + :keyword include_fresh_partial_cost: A boolean determining if FreshPartialCost will be + included. + :paramtype include_fresh_partial_cost: bool + """ + super().__init__(**kwargs) + self.type = type + self.timeframe = timeframe + self.time_period = time_period + self.dataset = dataset + self.include_actual_cost = include_actual_cost + self.include_fresh_partial_cost = include_fresh_partial_cost -class PivotProperties(msrest.serialization.Model): - """Each pivot must contain a 'type' and 'name'. +class ForecastFilter(_serialization.Model): + """The filter expression to be used in the export. - :param type: Data type to show in view. Possible values include: "Dimension", "TagKey". - :type type: str or ~azure.mgmt.costmanagement.models.PivotType - :param name: Data field to show in view. - :type name: str + :ivar and_property: The logical "AND" expression. Must have at least 2 items. + :vartype and_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :ivar or_property: The logical "OR" expression. Must have at least 2 items. + :vartype or_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :ivar dimensions: Has comparison expression for a dimension. + :vartype dimensions: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression + :ivar tags: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression """ + _validation = { + "and_property": {"min_items": 2}, + "or_property": {"min_items": 2}, + } + _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "and_property": {"key": "and", "type": "[ForecastFilter]"}, + "or_property": {"key": "or", "type": "[ForecastFilter]"}, + "dimensions": {"key": "dimensions", "type": "ForecastComparisonExpression"}, + "tags": {"key": "tags", "type": "ForecastComparisonExpression"}, } def __init__( self, *, - type: Optional[Union[str, "PivotType"]] = None, - name: Optional[str] = None, + and_property: Optional[List["_models.ForecastFilter"]] = None, + or_property: Optional[List["_models.ForecastFilter"]] = None, + dimensions: Optional["_models.ForecastComparisonExpression"] = None, + tags: Optional["_models.ForecastComparisonExpression"] = None, **kwargs ): - super(PivotProperties, self).__init__(**kwargs) - self.type = type - self.name = name + """ + :keyword and_property: The logical "AND" expression. Must have at least 2 items. + :paramtype and_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :keyword or_property: The logical "OR" expression. Must have at least 2 items. + :paramtype or_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :keyword dimensions: Has comparison expression for a dimension. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression + :keyword tags: Has comparison expression for a tag. + :paramtype tags: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression + """ + super().__init__(**kwargs) + self.and_property = and_property + self.or_property = or_property + self.dimensions = dimensions + self.tags = tags -class ProxySettingResource(msrest.serialization.Model): - """The Resource model definition. +class ForecastResult(Resource): + """Result of forecast. It contains all columns listed under groupings and aggregation. Variables are only populated by the server, and will be ignored when sending a request. @@ -1354,230 +2004,848 @@ class ProxySettingResource(msrest.serialization.Model): :vartype id: str :ivar name: Resource name. :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str :ivar type: Resource type. :vartype type: str + :ivar location: Location of the resource. + :vartype location: str + :ivar sku: SKU of the resource. + :vartype sku: str + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar next_link: The link (url) to the next page of results. + :vartype next_link: str + :ivar columns: Array of columns. + :vartype columns: list[~azure.mgmt.costmanagement.models.ForecastColumn] + :ivar rows: Array of rows. + :vartype rows: list[list[any]] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + "columns": {"key": "properties.columns", "type": "[ForecastColumn]"}, + "rows": {"key": "properties.rows", "type": "[[object]]"}, } def __init__( self, + *, + next_link: Optional[str] = None, + columns: Optional[List["_models.ForecastColumn"]] = None, + rows: Optional[List[List[Any]]] = None, **kwargs ): - super(ProxySettingResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.kind = None - self.type = None + """ + :keyword next_link: The link (url) to the next page of results. + :paramtype next_link: str + :keyword columns: Array of columns. + :paramtype columns: list[~azure.mgmt.costmanagement.models.ForecastColumn] + :keyword rows: Array of rows. + :paramtype rows: list[list[any]] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.columns = columns + self.rows = rows -class QueryAggregation(msrest.serialization.Model): - """The aggregation expression to be used in the query. +class ForecastTimePeriod(_serialization.Model): + """Has time period for pulling data for the forecast. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType + :ivar from_property: The start date to pull data from. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date to pull data to. Required. + :vartype to: ~datetime.datetime """ _validation = { - 'name': {'required': True}, - 'function': {'required': True}, + "from_property": {"required": True}, + "to": {"required": True}, + } + + _attribute_map = { + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, + } + + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date to pull data from. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date to pull data to. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) + self.from_property = from_property + self.to = to + + +class GenerateCostDetailsReportErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. + + Some Error responses: + + + * + 400 Bad Request - Invalid Request Payload. Request payload provided is not in a json format or had an invalid member not accepted in the request payload. + + * + 400 Bad Request - Invalid request payload: can only have either timePeriod or invoiceId or billingPeriod. API only allows data to be pulled for either timePeriod or invoiceId or billingPeriod. Customer should provide only one of these parameters. + + * + 400 Bad Request - Start date must be after . API only allows data to be pulled no older than 13 months from now. + + * + 400 Bad Request - The maximum allowed date range is 1 months. API only allows data to be pulled for 1 month or less. + + * + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "retry-after" header. + + * + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetails"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(**kwargs) + self.error = error + + +class GenerateCostDetailsReportRequestDefinition(_serialization.Model): + """The definition of a cost detailed report. + + :ivar metric: The type of the detailed report. By default ActualCost is provided. Known values + are: "ActualCost" and "AmortizedCost". + :vartype metric: str or ~azure.mgmt.costmanagement.models.CostDetailsMetricType + :ivar time_period: The specific date range of cost details requested for the report. This + parameter cannot be used alongside either the invoiceId or billingPeriod parameters. If a + timePeriod, invoiceId or billingPeriod parameter is not provided in the request body the API + will return the current month's cost. API only allows data to be pulled for 1 month or less and + no older than 13 months. If no timePeriod or billingPeriod or invoiceId is provided the API + defaults to the open month time period. + :vartype time_period: ~azure.mgmt.costmanagement.models.CostDetailsTimePeriod + :ivar billing_period: This parameter can be used only by Enterprise Agreement customers. Use + the YearMonth(e.g. 202008) format. This parameter cannot be used alongside either the invoiceId + or timePeriod parameters. If a timePeriod, invoiceId or billingPeriod parameter is not provided + in the request body the API will return the current month's cost. + :vartype billing_period: str + :ivar invoice_id: This parameter can only be used by Microsoft Customer Agreement customers. + Additionally, it can only be used at the Billing Profile or Customer scope. This parameter + cannot be used alongside either the billingPeriod or timePeriod parameters. If a timePeriod, + invoiceId or billingPeriod parameter is not provided in the request body the API will return + the current month's cost. + :vartype invoice_id: str + """ + + _attribute_map = { + "metric": {"key": "metric", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "CostDetailsTimePeriod"}, + "billing_period": {"key": "billingPeriod", "type": "str"}, + "invoice_id": {"key": "invoiceId", "type": "str"}, } + def __init__( + self, + *, + metric: Optional[Union[str, "_models.CostDetailsMetricType"]] = None, + time_period: Optional["_models.CostDetailsTimePeriod"] = None, + billing_period: Optional[str] = None, + invoice_id: Optional[str] = None, + **kwargs + ): + """ + :keyword metric: The type of the detailed report. By default ActualCost is provided. Known + values are: "ActualCost" and "AmortizedCost". + :paramtype metric: str or ~azure.mgmt.costmanagement.models.CostDetailsMetricType + :keyword time_period: The specific date range of cost details requested for the report. This + parameter cannot be used alongside either the invoiceId or billingPeriod parameters. If a + timePeriod, invoiceId or billingPeriod parameter is not provided in the request body the API + will return the current month's cost. API only allows data to be pulled for 1 month or less and + no older than 13 months. If no timePeriod or billingPeriod or invoiceId is provided the API + defaults to the open month time period. + :paramtype time_period: ~azure.mgmt.costmanagement.models.CostDetailsTimePeriod + :keyword billing_period: This parameter can be used only by Enterprise Agreement customers. Use + the YearMonth(e.g. 202008) format. This parameter cannot be used alongside either the invoiceId + or timePeriod parameters. If a timePeriod, invoiceId or billingPeriod parameter is not provided + in the request body the API will return the current month's cost. + :paramtype billing_period: str + :keyword invoice_id: This parameter can only be used by Microsoft Customer Agreement customers. + Additionally, it can only be used at the Billing Profile or Customer scope. This parameter + cannot be used alongside either the billingPeriod or timePeriod parameters. If a timePeriod, + invoiceId or billingPeriod parameter is not provided in the request body the API will return + the current month's cost. + :paramtype invoice_id: str + """ + super().__init__(**kwargs) + self.metric = metric + self.time_period = time_period + self.billing_period = billing_period + self.invoice_id = invoice_id + + +class GenerateDetailedCostReportDefinition(_serialization.Model): + """The definition of a cost detailed report. + + :ivar metric: The type of the detailed report. By default ActualCost is provided. Known values + are: "ActualCost" and "AmortizedCost". + :vartype metric: str or ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportMetricType + :ivar time_period: Has time period for pulling data for the cost detailed report. Can only have + one of either timePeriod or invoiceId or billingPeriod parameters. If none provided current + month cost is provided. + :vartype time_period: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportTimePeriod + :ivar billing_period: Billing Period in YearMonth(e.g. 202008) format. Only for legacy + enterprise customers can use this. Can only have one of either timePeriod or invoiceId or + billingPeriod parameters. If none provided current month cost is provided. + :vartype billing_period: str + :ivar invoice_id: Invoice Id for PayAsYouGo customers and Modern billing profile scope. Can + only have one of either timePeriod or invoiceId or billingPeriod parameters. If none provided + current month cost is provided. + :vartype invoice_id: str + :ivar customer_id: Customer Id for Modern (Invoice Id and billing profile is also required for + this). + :vartype customer_id: str + """ + _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, + "metric": {"key": "metric", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "GenerateDetailedCostReportTimePeriod"}, + "billing_period": {"key": "billingPeriod", "type": "str"}, + "invoice_id": {"key": "invoiceId", "type": "str"}, + "customer_id": {"key": "customerId", "type": "str"}, } def __init__( self, *, - name: str, - function: Union[str, "FunctionType"], + metric: Optional[Union[str, "_models.GenerateDetailedCostReportMetricType"]] = None, + time_period: Optional["_models.GenerateDetailedCostReportTimePeriod"] = None, + billing_period: Optional[str] = None, + invoice_id: Optional[str] = None, + customer_id: Optional[str] = None, **kwargs ): - super(QueryAggregation, self).__init__(**kwargs) + """ + :keyword metric: The type of the detailed report. By default ActualCost is provided. Known + values are: "ActualCost" and "AmortizedCost". + :paramtype metric: str or + ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportMetricType + :keyword time_period: Has time period for pulling data for the cost detailed report. Can only + have one of either timePeriod or invoiceId or billingPeriod parameters. If none provided + current month cost is provided. + :paramtype time_period: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportTimePeriod + :keyword billing_period: Billing Period in YearMonth(e.g. 202008) format. Only for legacy + enterprise customers can use this. Can only have one of either timePeriod or invoiceId or + billingPeriod parameters. If none provided current month cost is provided. + :paramtype billing_period: str + :keyword invoice_id: Invoice Id for PayAsYouGo customers and Modern billing profile scope. Can + only have one of either timePeriod or invoiceId or billingPeriod parameters. If none provided + current month cost is provided. + :paramtype invoice_id: str + :keyword customer_id: Customer Id for Modern (Invoice Id and billing profile is also required + for this). + :paramtype customer_id: str + """ + super().__init__(**kwargs) + self.metric = metric + self.time_period = time_period + self.billing_period = billing_period + self.invoice_id = invoice_id + self.customer_id = customer_id + + +class GenerateDetailedCostReportErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. + + Some Error responses: + + + * + 413 Request Entity Too Large - Request is throttled. The amount of data required to fulfill the request exceeds the maximum size permitted of 2Gb. Please utilize our Exports feature instead. + + * + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. + + * + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetails"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(**kwargs) + self.error = error + + +class GenerateDetailedCostReportOperationResult(_serialization.Model): + """The result of the long running operation for cost detailed report. + + :ivar id: The id of the long running operation. + :vartype id: str + :ivar name: The name of the long running operation. + :vartype name: str + :ivar type: The type of the long running operation. + :vartype type: str + :ivar download_url: The URL to download the generated report. + :vartype download_url: str + :ivar valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype valid_till: ~datetime.datetime + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "download_url": {"key": "properties.downloadUrl", "type": "str"}, + "valid_till": {"key": "properties.validTill", "type": "iso-8601"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + type: Optional[str] = None, + download_url: Optional[str] = None, + valid_till: Optional[datetime.datetime] = None, + **kwargs + ): + """ + :keyword id: The id of the long running operation. + :paramtype id: str + :keyword name: The name of the long running operation. + :paramtype name: str + :keyword type: The type of the long running operation. + :paramtype type: str + :keyword download_url: The URL to download the generated report. + :paramtype download_url: str + :keyword valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :paramtype valid_till: ~datetime.datetime + """ + super().__init__(**kwargs) + self.id = id self.name = name - self.function = function + self.type = type + self.download_url = download_url + self.valid_till = valid_till -class QueryColumn(msrest.serialization.Model): - """QueryColumn. +class GenerateDetailedCostReportOperationStatuses(_serialization.Model): + """The status of the long running operation for cost detailed report. - :param name: The name of column. - :type name: str - :param type: The type of column. - :type type: str + :ivar id: The id of the long running operation. + :vartype id: str + :ivar name: The name of the long running operation. + :vartype name: str + :ivar status: The status of the long running operation. + :vartype status: ~azure.mgmt.costmanagement.models.Status + :ivar type: The type of the long running operation. + :vartype type: str + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :ivar download_url: The URL to download the generated report. + :vartype download_url: str + :ivar valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype valid_till: ~datetime.datetime """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "status": {"key": "status", "type": "Status"}, + "type": {"key": "type", "type": "str"}, + "error": {"key": "error", "type": "ErrorDetails"}, + "download_url": {"key": "properties.downloadUrl", "type": "str"}, + "valid_till": {"key": "properties.validTill", "type": "iso-8601"}, } def __init__( self, *, + id: Optional[str] = None, # pylint: disable=redefined-builtin name: Optional[str] = None, + status: Optional["_models.Status"] = None, type: Optional[str] = None, + error: Optional["_models.ErrorDetails"] = None, + download_url: Optional[str] = None, + valid_till: Optional[datetime.datetime] = None, **kwargs ): - super(QueryColumn, self).__init__(**kwargs) + """ + :keyword id: The id of the long running operation. + :paramtype id: str + :keyword name: The name of the long running operation. + :paramtype name: str + :keyword status: The status of the long running operation. + :paramtype status: ~azure.mgmt.costmanagement.models.Status + :keyword type: The type of the long running operation. + :paramtype type: str + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :keyword download_url: The URL to download the generated report. + :paramtype download_url: str + :keyword valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :paramtype valid_till: ~datetime.datetime + """ + super().__init__(**kwargs) + self.id = id self.name = name + self.status = status self.type = type + self.error = error + self.download_url = download_url + self.valid_till = valid_till -class QueryComparisonExpression(msrest.serialization.Model): - """The comparison expression to be used in the query. +class GenerateDetailedCostReportTimePeriod(_serialization.Model): + """The start and end date for pulling data for the cost detailed report. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", - "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] + :ivar start: The start date to pull data from. example format 2020-03-15. Required. + :vartype start: str + :ivar end: The end date to pull data to. example format 2020-03-15. Required. + :vartype end: str """ _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, + "start": {"required": True}, + "end": {"required": True}, + } + + _attribute_map = { + "start": {"key": "start", "type": "str"}, + "end": {"key": "end", "type": "str"}, } + def __init__(self, *, start: str, end: str, **kwargs): + """ + :keyword start: The start date to pull data from. example format 2020-03-15. Required. + :paramtype start: str + :keyword end: The end date to pull data to. example format 2020-03-15. Required. + :paramtype end: str + """ + super().__init__(**kwargs) + self.start = start + self.end = end + + +class KpiProperties(_serialization.Model): + """Each KPI must contain a 'type' and 'enabled' key. + + :ivar type: KPI type (Forecast, Budget). Known values are: "Forecast" and "Budget". + :vartype type: str or ~azure.mgmt.costmanagement.models.KpiType + :ivar id: ID of resource related to metric (budget). + :vartype id: str + :ivar enabled: show the KPI in the UI?. + :vartype enabled: bool + """ + _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "enabled": {"key": "enabled", "type": "bool"}, } def __init__( self, *, - name: str, - operator: Union[str, "OperatorType"], - values: List[str], + type: Optional[Union[str, "_models.KpiType"]] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + enabled: Optional[bool] = None, **kwargs ): - super(QueryComparisonExpression, self).__init__(**kwargs) - self.name = name - self.operator = operator - self.values = values + """ + :keyword type: KPI type (Forecast, Budget). Known values are: "Forecast" and "Budget". + :paramtype type: str or ~azure.mgmt.costmanagement.models.KpiType + :keyword id: ID of resource related to metric (budget). + :paramtype id: str + :keyword enabled: show the KPI in the UI?. + :paramtype enabled: bool + """ + super().__init__(**kwargs) + self.type = type + self.id = id + self.enabled = enabled -class QueryDataset(msrest.serialization.Model): - """The definition of data present in the query. +class Operation(_serialization.Model): + """A Cost management REST API operation. - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each - item in the dictionary is the alias for the aggregated column. Query can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group - by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST - documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilter + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Operation id: {provider}/{resource}/{operation}. + :vartype id: str + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.costmanagement.models.OperationDisplay + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): + """ + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.costmanagement.models.OperationDisplay + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.display = display + + +class OperationDisplay(_serialization.Model): + """The object that represents the operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provider: Service provider: Microsoft.CostManagement. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: Dimensions, Query. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str """ _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilter'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None + + +class OperationListResult(_serialization.Model): + """Result of listing cost management operations. It contains a list of operations and a URL link to get the next set of results. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: List of cost management operations supported by the Microsoft.CostManagement + resource provider. + :vartype value: list[~azure.mgmt.costmanagement.models.Operation] + :ivar next_link: URL to get the next set of operation list results if there are any. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class OperationStatus(_serialization.Model): + """The status of the long running operation. + + :ivar status: The status of the long running operation. Known values are: "Running", + "Completed", and "Failed". + :vartype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :ivar report_url: The CSV file from the reportUrl blob link consists of reservation usage data + with the following schema at daily granularity. Known values are: "InstanceFlexibilityGroup", + "InstanceFlexibilityRatio", "InstanceId", "Kind", "ReservationId", "ReservationOrderId", + "ReservedHours", "SkuName", "TotalReservedQuantity", "UsageDate", and "UsedHours". + :vartype report_url: str or ~azure.mgmt.costmanagement.models.ReservationReportSchema + :ivar valid_until: The time at which report URL becomes invalid. + :vartype valid_until: ~datetime.datetime + """ + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "report_url": {"key": "properties.reportUrl", "type": "str"}, + "valid_until": {"key": "properties.validUntil", "type": "iso-8601"}, } def __init__( self, *, - granularity: Optional[Union[str, "GranularityType"]] = None, - configuration: Optional["QueryDatasetConfiguration"] = None, - aggregation: Optional[Dict[str, "QueryAggregation"]] = None, - grouping: Optional[List["QueryGrouping"]] = None, - filter: Optional["QueryFilter"] = None, + status: Optional[Union[str, "_models.OperationStatusType"]] = None, + report_url: Optional[Union[str, "_models.ReservationReportSchema"]] = None, + valid_until: Optional[datetime.datetime] = None, **kwargs ): - super(QueryDataset, self).__init__(**kwargs) - self.granularity = granularity - self.configuration = configuration - self.aggregation = aggregation - self.grouping = grouping - self.filter = filter + """ + :keyword status: The status of the long running operation. Known values are: "Running", + "Completed", and "Failed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :keyword report_url: The CSV file from the reportUrl blob link consists of reservation usage + data with the following schema at daily granularity. Known values are: + "InstanceFlexibilityGroup", "InstanceFlexibilityRatio", "InstanceId", "Kind", "ReservationId", + "ReservationOrderId", "ReservedHours", "SkuName", "TotalReservedQuantity", "UsageDate", and + "UsedHours". + :paramtype report_url: str or ~azure.mgmt.costmanagement.models.ReservationReportSchema + :keyword valid_until: The time at which report URL becomes invalid. + :paramtype valid_until: ~datetime.datetime + """ + super().__init__(**kwargs) + self.status = status + self.report_url = report_url + self.valid_until = valid_until + + +class PivotProperties(_serialization.Model): + """Each pivot must contain a 'type' and 'name'. + + :ivar type: Data type to show in view. Known values are: "Dimension" and "TagKey". + :vartype type: str or ~azure.mgmt.costmanagement.models.PivotType + :ivar name: Data field to show in view. + :vartype name: str + """ + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + } + + def __init__(self, *, type: Optional[Union[str, "_models.PivotType"]] = None, name: Optional[str] = None, **kwargs): + """ + :keyword type: Data type to show in view. Known values are: "Dimension" and "TagKey". + :paramtype type: str or ~azure.mgmt.costmanagement.models.PivotType + :keyword name: Data field to show in view. + :paramtype name: str + """ + super().__init__(**kwargs) + self.type = type + self.name = name + + +class QueryAggregation(_serialization.Model): + """The aggregation expression to be used in the query. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The name of the column to aggregate. Required. + :vartype name: str + :ivar function: The name of the aggregation function to use. Required. "Sum" + :vartype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + + _validation = { + "name": {"required": True}, + "function": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "function": {"key": "function", "type": "str"}, + } + + def __init__(self, *, name: str, function: Union[str, "_models.FunctionType"], **kwargs): + """ + :keyword name: The name of the column to aggregate. Required. + :paramtype name: str + :keyword function: The name of the aggregation function to use. Required. "Sum" + :paramtype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + super().__init__(**kwargs) + self.name = name + self.function = function + + +class QueryColumn(_serialization.Model): + """QueryColumn properties. + + :ivar name: The name of column. + :vartype name: str + :ivar type: The type of column. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword name: The name of column. + :paramtype name: str + :keyword type: The type of column. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class QueryComparisonExpression(_serialization.Model): + """The comparison expression to be used in the query. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The name of the column to use in comparison. Required. + :vartype name: str + :ivar operator: The operator to use for comparison. Required. "In" + :vartype operator: str or ~azure.mgmt.costmanagement.models.QueryOperatorType + :ivar values: Array of values to use for comparison. Required. + :vartype values: list[str] + """ + + _validation = { + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True, "min_items": 1}, + } + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__(self, *, name: str, operator: Union[str, "_models.QueryOperatorType"], values: List[str], **kwargs): + """ + :keyword name: The name of the column to use in comparison. Required. + :paramtype name: str + :keyword operator: The operator to use for comparison. Required. "In" + :paramtype operator: str or ~azure.mgmt.costmanagement.models.QueryOperatorType + :keyword values: Array of values to use for comparison. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) + self.name = name + self.operator = operator + self.values = values -class QueryDatasetAutoGenerated(msrest.serialization.Model): + +class QueryDataset(_serialization.Model): """The definition of data present in the query. - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The + :ivar granularity: The granularity of rows in the query. "Daily" + :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :ivar configuration: Has configuration information for the data in the export. The configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each + :vartype configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration + :ivar aggregation: Dictionary of aggregation expression to use in the query. The key of each item in the dictionary is the alias for the aggregated column. Query can have up to 2 aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group + :vartype aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] + :ivar grouping: Array of group by expression to use in the query. Query can have up to 2 group by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST + :vartype grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] + :ivar filter: The filter expression to use in the query. Please reference our Query API REST documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated + :vartype filter: ~azure.mgmt.costmanagement.models.QueryFilter """ _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, + "grouping": {"max_items": 2, "min_items": 0}, } _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilterAutoGenerated'}, + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "QueryDatasetConfiguration"}, + "aggregation": {"key": "aggregation", "type": "{QueryAggregation}"}, + "grouping": {"key": "grouping", "type": "[QueryGrouping]"}, + "filter": {"key": "filter", "type": "QueryFilter"}, } def __init__( self, *, - granularity: Optional[Union[str, "GranularityType"]] = None, - configuration: Optional["QueryDatasetConfiguration"] = None, - aggregation: Optional[Dict[str, "QueryAggregation"]] = None, - grouping: Optional[List["QueryGrouping"]] = None, - filter: Optional["QueryFilterAutoGenerated"] = None, + granularity: Optional[Union[str, "_models.GranularityType"]] = None, + configuration: Optional["_models.QueryDatasetConfiguration"] = None, + aggregation: Optional[Dict[str, "_models.QueryAggregation"]] = None, + grouping: Optional[List["_models.QueryGrouping"]] = None, + filter: Optional["_models.QueryFilter"] = None, # pylint: disable=redefined-builtin **kwargs ): - super(QueryDatasetAutoGenerated, self).__init__(**kwargs) + """ + :keyword granularity: The granularity of rows in the query. "Daily" + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :keyword configuration: Has configuration information for the data in the export. The + configuration will be ignored if aggregation and grouping are provided. + :paramtype configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration + :keyword aggregation: Dictionary of aggregation expression to use in the query. The key of each + item in the dictionary is the alias for the aggregated column. Query can have up to 2 + aggregation clauses. + :paramtype aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] + :keyword grouping: Array of group by expression to use in the query. Query can have up to 2 + group by clauses. + :paramtype grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] + :keyword filter: The filter expression to use in the query. Please reference our Query API REST + documentation for how to properly format the filter. + :paramtype filter: ~azure.mgmt.costmanagement.models.QueryFilter + """ + super().__init__(**kwargs) self.granularity = granularity self.configuration = configuration self.aggregation = aggregation @@ -1585,187 +2853,169 @@ def __init__( self.filter = filter -class QueryDatasetConfiguration(msrest.serialization.Model): +class QueryDatasetConfiguration(_serialization.Model): """The configuration of dataset in the query. - :param columns: Array of column names to be included in the query. Any valid query column name + :ivar columns: Array of column names to be included in the query. Any valid query column name is allowed. If not provided, then query includes all columns. - :type columns: list[str] + :vartype columns: list[str] """ _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, + "columns": {"key": "columns", "type": "[str]"}, } - def __init__( - self, - *, - columns: Optional[List[str]] = None, - **kwargs - ): - super(QueryDatasetConfiguration, self).__init__(**kwargs) + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the query. Any valid query column + name is allowed. If not provided, then query includes all columns. + :paramtype columns: list[str] + """ + super().__init__(**kwargs) self.columns = columns -class QueryDefinition(msrest.serialization.Model): +class QueryDefinition(_serialization.Model): """The definition of a query. All required parameters must be populated in order to send to Azure. - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", + :ivar type: The type of the query. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this query. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset + :vartype type: str or ~azure.mgmt.costmanagement.models.ExportType + :ivar timeframe: The time frame for pulling data for the query. If custom, then a specific time + period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :ivar time_period: Has time period for pulling data for the query. + :vartype time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod + :ivar dataset: Has definition for data in this query. Required. + :vartype dataset: ~azure.mgmt.costmanagement.models.QueryDataset """ _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, + "type": {"required": True}, + "timeframe": {"required": True}, + "dataset": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, + "type": {"key": "type", "type": "str"}, + "timeframe": {"key": "timeframe", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "QueryTimePeriod"}, + "dataset": {"key": "dataset", "type": "QueryDataset"}, } def __init__( self, *, - type: Union[str, "ExportType"], - timeframe: Union[str, "TimeframeType"], - dataset: "QueryDataset", - time_period: Optional["QueryTimePeriod"] = None, + type: Union[str, "_models.ExportType"], + timeframe: Union[str, "_models.TimeframeType"], + dataset: "_models.QueryDataset", + time_period: Optional["_models.QueryTimePeriod"] = None, **kwargs ): - super(QueryDefinition, self).__init__(**kwargs) + """ + :keyword type: The type of the query. Required. Known values are: "Usage", "ActualCost", and + "AmortizedCost". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ExportType + :keyword timeframe: The time frame for pulling data for the query. If custom, then a specific + time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :keyword time_period: Has time period for pulling data for the query. + :paramtype time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod + :keyword dataset: Has definition for data in this query. Required. + :paramtype dataset: ~azure.mgmt.costmanagement.models.QueryDataset + """ + super().__init__(**kwargs) self.type = type self.timeframe = timeframe self.time_period = time_period self.dataset = dataset -class QueryFilter(msrest.serialization.Model): - """The filter expression to be used in the export. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilter]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, - } - - def __init__( - self, - *, - and_property: Optional[List["QueryFilter"]] = None, - or_property: Optional[List["QueryFilter"]] = None, - dimensions: Optional["QueryComparisonExpression"] = None, - tags: Optional["QueryComparisonExpression"] = None, - **kwargs - ): - super(QueryFilter, self).__init__(**kwargs) - self.and_property = and_property - self.or_property = or_property - self.dimensions = dimensions - self.tags = tags - - -class QueryFilterAutoGenerated(msrest.serialization.Model): +class QueryFilter(_serialization.Model): """The filter expression to be used in the export. - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + :ivar and_property: The logical "AND" expression. Must have at least 2 items. + :vartype and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :ivar or_property: The logical "OR" expression. Must have at least 2 items. + :vartype or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :ivar dimensions: Has comparison expression for a dimension. + :vartype dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + :ivar tags: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression """ _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, + "and_property": {"min_items": 2}, + "or_property": {"min_items": 2}, } _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilterAutoGenerated]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilterAutoGenerated]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, + "and_property": {"key": "and", "type": "[QueryFilter]"}, + "or_property": {"key": "or", "type": "[QueryFilter]"}, + "dimensions": {"key": "dimensions", "type": "QueryComparisonExpression"}, + "tags": {"key": "tags", "type": "QueryComparisonExpression"}, } def __init__( self, *, - and_property: Optional[List["QueryFilterAutoGenerated"]] = None, - or_property: Optional[List["QueryFilterAutoGenerated"]] = None, - dimensions: Optional["QueryComparisonExpression"] = None, - tags: Optional["QueryComparisonExpression"] = None, + and_property: Optional[List["_models.QueryFilter"]] = None, + or_property: Optional[List["_models.QueryFilter"]] = None, + dimensions: Optional["_models.QueryComparisonExpression"] = None, + tags: Optional["_models.QueryComparisonExpression"] = None, **kwargs ): - super(QueryFilterAutoGenerated, self).__init__(**kwargs) + """ + :keyword and_property: The logical "AND" expression. Must have at least 2 items. + :paramtype and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :keyword or_property: The logical "OR" expression. Must have at least 2 items. + :paramtype or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :keyword dimensions: Has comparison expression for a dimension. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + :keyword tags: Has comparison expression for a tag. + :paramtype tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + """ + super().__init__(**kwargs) self.and_property = and_property self.or_property = or_property self.dimensions = dimensions self.tags = tags -class QueryGrouping(msrest.serialization.Model): +class QueryGrouping(_serialization.Model): """The group by expression to be used in the query. All required parameters must be populated in order to send to Azure. - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.QueryColumnType - :param name: Required. The name of the column to group. - :type name: str + :ivar type: Has type of the column to group. Required. Known values are: "Tag" and "Dimension". + :vartype type: str or ~azure.mgmt.costmanagement.models.QueryColumnType + :ivar name: The name of the column to group. Required. + :vartype name: str """ _validation = { - 'type': {'required': True}, - 'name': {'required': True}, + "type": {"required": True}, + "name": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - *, - type: Union[str, "QueryColumnType"], - name: str, - **kwargs - ): - super(QueryGrouping, self).__init__(**kwargs) + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + } + + def __init__(self, *, type: Union[str, "_models.QueryColumnType"], name: str, **kwargs): + """ + :keyword type: Has type of the column to group. Required. Known values are: "Tag" and + "Dimension". + :paramtype type: str or ~azure.mgmt.costmanagement.models.QueryColumnType + :keyword name: The name of the column to group. Required. + :paramtype name: str + """ + super().__init__(**kwargs) self.type = type self.name = name @@ -1781,217 +3031,241 @@ class QueryResult(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :ivar location: Resource location. + :ivar location: Location of the resource. :vartype location: str - :ivar sku: Resource SKU. + :ivar sku: SKU of the resource. :vartype sku: str - :param next_link: The link (url) to the next page of results. - :type next_link: str - :param columns: Array of columns. - :type columns: list[~azure.mgmt.costmanagement.models.QueryColumn] - :param rows: Array of rows. - :type rows: list[list[any]] + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar next_link: The link (url) to the next page of results. + :vartype next_link: str + :ivar columns: Array of columns. + :vartype columns: list[~azure.mgmt.costmanagement.models.QueryColumn] + :ivar rows: Array of rows. + :vartype rows: list[list[any]] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'location': {'readonly': True}, - 'sku': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - 'columns': {'key': 'properties.columns', 'type': '[QueryColumn]'}, - 'rows': {'key': 'properties.rows', 'type': '[[object]]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + "columns": {"key": "properties.columns", "type": "[QueryColumn]"}, + "rows": {"key": "properties.rows", "type": "[[object]]"}, } def __init__( self, *, - e_tag: Optional[str] = None, next_link: Optional[str] = None, - columns: Optional[List["QueryColumn"]] = None, + columns: Optional[List["_models.QueryColumn"]] = None, rows: Optional[List[List[Any]]] = None, **kwargs ): - super(QueryResult, self).__init__(**kwargs) - self.e_tag = e_tag - self.location = None - self.sku = None + """ + :keyword next_link: The link (url) to the next page of results. + :paramtype next_link: str + :keyword columns: Array of columns. + :paramtype columns: list[~azure.mgmt.costmanagement.models.QueryColumn] + :keyword rows: Array of rows. + :paramtype rows: list[list[any]] + """ + super().__init__(**kwargs) self.next_link = next_link self.columns = columns self.rows = rows -class QueryTimePeriod(msrest.serialization.Model): +class QueryTimePeriod(_serialization.Model): """The start and end date for pulling data for the query. All required parameters must be populated in order to send to Azure. - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime + :ivar from_property: The start date to pull data from. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date to pull data to. Required. + :vartype to: ~datetime.datetime """ _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, + "from_property": {"required": True}, + "to": {"required": True}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - *, - from_property: datetime.datetime, - to: datetime.datetime, - **kwargs - ): - super(QueryTimePeriod, self).__init__(**kwargs) + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, + } + + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date to pull data from. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date to pull data to. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) self.from_property = from_property self.to = to -class ReportConfigAggregation(msrest.serialization.Model): +class ReportConfigAggregation(_serialization.Model): """The aggregation expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType + :ivar name: The name of the column to aggregate. Required. + :vartype name: str + :ivar function: The name of the aggregation function to use. Required. "Sum" + :vartype function: str or ~azure.mgmt.costmanagement.models.FunctionType """ _validation = { - 'name': {'required': True}, - 'function': {'required': True}, + "name": {"required": True}, + "function": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, - } - - def __init__( - self, - *, - name: str, - function: Union[str, "FunctionType"], - **kwargs - ): - super(ReportConfigAggregation, self).__init__(**kwargs) + "name": {"key": "name", "type": "str"}, + "function": {"key": "function", "type": "str"}, + } + + def __init__(self, *, name: str, function: Union[str, "_models.FunctionType"], **kwargs): + """ + :keyword name: The name of the column to aggregate. Required. + :paramtype name: str + :keyword function: The name of the aggregation function to use. Required. "Sum" + :paramtype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + super().__init__(**kwargs) self.name = name self.function = function -class ReportConfigComparisonExpression(msrest.serialization.Model): +class ReportConfigComparisonExpression(_serialization.Model): """The comparison expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", + :ivar name: The name of the column to use in comparison. Required. + :vartype name: str + :ivar operator: The operator to use for comparison. Required. Known values are: "In" and "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] + :vartype operator: str or ~azure.mgmt.costmanagement.models.OperatorType + :ivar values: Array of values to use for comparison. Required. + :vartype values: list[str] """ _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True, "min_items": 1}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - } - - def __init__( - self, - *, - name: str, - operator: Union[str, "OperatorType"], - values: List[str], - **kwargs - ): - super(ReportConfigComparisonExpression, self).__init__(**kwargs) + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__(self, *, name: str, operator: Union[str, "_models.OperatorType"], values: List[str], **kwargs): + """ + :keyword name: The name of the column to use in comparison. Required. + :paramtype name: str + :keyword operator: The operator to use for comparison. Required. Known values are: "In" and + "Contains". + :paramtype operator: str or ~azure.mgmt.costmanagement.models.OperatorType + :keyword values: Array of values to use for comparison. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) self.name = name self.operator = operator self.values = values -class ReportConfigDataset(msrest.serialization.Model): +class ReportConfigDataset(_serialization.Model): """The definition of data present in the report. - :param granularity: The granularity of rows in the report. Possible values include: "Daily", + :ivar granularity: The granularity of rows in the report. Known values are: "Daily" and "Monthly". - :type granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType - :param configuration: Has configuration information for the data in the report. The + :vartype granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType + :ivar configuration: Has configuration information for the data in the report. The configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the report. The key of each + :vartype configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration + :ivar aggregation: Dictionary of aggregation expression to use in the report. The key of each item in the dictionary is the alias for the aggregated column. Report can have up to 2 aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] - :param grouping: Array of group by expression to use in the report. Report can have up to 2 + :vartype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] + :ivar grouping: Array of group by expression to use in the report. Report can have up to 2 group by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] - :param sorting: Array of order by expression to use in the report. - :type sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] - :param filter: Has filter expression to use in the report. - :type filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter + :vartype grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] + :ivar sorting: Array of order by expression to use in the report. + :vartype sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] + :ivar filter: Has filter expression to use in the report. + :vartype filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter """ _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, + "grouping": {"max_items": 2, "min_items": 0}, } _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'ReportConfigDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{ReportConfigAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[ReportConfigGrouping]'}, - 'sorting': {'key': 'sorting', 'type': '[ReportConfigSorting]'}, - 'filter': {'key': 'filter', 'type': 'ReportConfigFilter'}, + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "ReportConfigDatasetConfiguration"}, + "aggregation": {"key": "aggregation", "type": "{ReportConfigAggregation}"}, + "grouping": {"key": "grouping", "type": "[ReportConfigGrouping]"}, + "sorting": {"key": "sorting", "type": "[ReportConfigSorting]"}, + "filter": {"key": "filter", "type": "ReportConfigFilter"}, } def __init__( self, *, - granularity: Optional[Union[str, "ReportGranularityType"]] = None, - configuration: Optional["ReportConfigDatasetConfiguration"] = None, - aggregation: Optional[Dict[str, "ReportConfigAggregation"]] = None, - grouping: Optional[List["ReportConfigGrouping"]] = None, - sorting: Optional[List["ReportConfigSorting"]] = None, - filter: Optional["ReportConfigFilter"] = None, + granularity: Optional[Union[str, "_models.ReportGranularityType"]] = None, + configuration: Optional["_models.ReportConfigDatasetConfiguration"] = None, + aggregation: Optional[Dict[str, "_models.ReportConfigAggregation"]] = None, + grouping: Optional[List["_models.ReportConfigGrouping"]] = None, + sorting: Optional[List["_models.ReportConfigSorting"]] = None, + filter: Optional["_models.ReportConfigFilter"] = None, # pylint: disable=redefined-builtin **kwargs ): - super(ReportConfigDataset, self).__init__(**kwargs) + """ + :keyword granularity: The granularity of rows in the report. Known values are: "Daily" and + "Monthly". + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType + :keyword configuration: Has configuration information for the data in the report. The + configuration will be ignored if aggregation and grouping are provided. + :paramtype configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration + :keyword aggregation: Dictionary of aggregation expression to use in the report. The key of + each item in the dictionary is the alias for the aggregated column. Report can have up to 2 + aggregation clauses. + :paramtype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] + :keyword grouping: Array of group by expression to use in the report. Report can have up to 2 + group by clauses. + :paramtype grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] + :keyword sorting: Array of order by expression to use in the report. + :paramtype sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] + :keyword filter: Has filter expression to use in the report. + :paramtype filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter + """ + super().__init__(**kwargs) self.granularity = granularity self.configuration = configuration self.aggregation = aggregation @@ -2000,287 +3274,205 @@ def __init__( self.filter = filter -class ReportConfigDatasetConfiguration(msrest.serialization.Model): +class ReportConfigDatasetConfiguration(_serialization.Model): """The configuration of dataset in the report. - :param columns: Array of column names to be included in the report. Any valid report column - name is allowed. If not provided, then report includes all columns. - :type columns: list[str] + :ivar columns: Array of column names to be included in the report. Any valid report column name + is allowed. If not provided, then report includes all columns. + :vartype columns: list[str] """ _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, + "columns": {"key": "columns", "type": "[str]"}, } - def __init__( - self, - *, - columns: Optional[List[str]] = None, - **kwargs - ): - super(ReportConfigDatasetConfiguration, self).__init__(**kwargs) + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the report. Any valid report column + name is allowed. If not provided, then report includes all columns. + :paramtype columns: list[str] + """ + super().__init__(**kwargs) self.columns = columns -class ReportConfigFilter(msrest.serialization.Model): +class ReportConfigFilter(_serialization.Model): """The filter expression to be used in the report. - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_key: Has comparison expression for a tag key. - :type tag_key: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_value: Has comparison expression for a tag value. - :type tag_value: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + :ivar and_property: The logical "AND" expression. Must have at least 2 items. + :vartype and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :ivar or_property: The logical "OR" expression. Must have at least 2 items. + :vartype or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :ivar dimensions: Has comparison expression for a dimension. + :vartype dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + :ivar tags: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression """ _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, + "and_property": {"min_items": 2}, + "or_property": {"min_items": 2}, } _attribute_map = { - 'and_property': {'key': 'and', 'type': '[ReportConfigFilter]'}, - 'or_property': {'key': 'or', 'type': '[ReportConfigFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'ReportConfigComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'ReportConfigComparisonExpression'}, - 'tag_key': {'key': 'tagKey', 'type': 'ReportConfigComparisonExpression'}, - 'tag_value': {'key': 'tagValue', 'type': 'ReportConfigComparisonExpression'}, + "and_property": {"key": "and", "type": "[ReportConfigFilter]"}, + "or_property": {"key": "or", "type": "[ReportConfigFilter]"}, + "dimensions": {"key": "dimensions", "type": "ReportConfigComparisonExpression"}, + "tags": {"key": "tags", "type": "ReportConfigComparisonExpression"}, } def __init__( self, *, - and_property: Optional[List["ReportConfigFilter"]] = None, - or_property: Optional[List["ReportConfigFilter"]] = None, - dimensions: Optional["ReportConfigComparisonExpression"] = None, - tags: Optional["ReportConfigComparisonExpression"] = None, - tag_key: Optional["ReportConfigComparisonExpression"] = None, - tag_value: Optional["ReportConfigComparisonExpression"] = None, + and_property: Optional[List["_models.ReportConfigFilter"]] = None, + or_property: Optional[List["_models.ReportConfigFilter"]] = None, + dimensions: Optional["_models.ReportConfigComparisonExpression"] = None, + tags: Optional["_models.ReportConfigComparisonExpression"] = None, **kwargs ): - super(ReportConfigFilter, self).__init__(**kwargs) + """ + :keyword and_property: The logical "AND" expression. Must have at least 2 items. + :paramtype and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :keyword or_property: The logical "OR" expression. Must have at least 2 items. + :paramtype or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :keyword dimensions: Has comparison expression for a dimension. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + :keyword tags: Has comparison expression for a tag. + :paramtype tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + """ + super().__init__(**kwargs) self.and_property = and_property self.or_property = or_property self.dimensions = dimensions self.tags = tags - self.tag_key = tag_key - self.tag_value = tag_value -class ReportConfigGrouping(msrest.serialization.Model): +class ReportConfigGrouping(_serialization.Model): """The group by expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType - :param name: Required. The name of the column to group. This version supports subscription - lowest possible grain. - :type name: str + :ivar type: Has type of the column to group. Required. Known values are: "Tag" and "Dimension". + :vartype type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType + :ivar name: The name of the column to group. This version supports subscription lowest possible + grain. Required. + :vartype name: str """ _validation = { - 'type': {'required': True}, - 'name': {'required': True}, + "type": {"required": True}, + "name": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - *, - type: Union[str, "ReportConfigColumnType"], - name: str, - **kwargs - ): - super(ReportConfigGrouping, self).__init__(**kwargs) + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + } + + def __init__(self, *, type: Union[str, "_models.ReportConfigColumnType"], name: str, **kwargs): + """ + :keyword type: Has type of the column to group. Required. Known values are: "Tag" and + "Dimension". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType + :keyword name: The name of the column to group. This version supports subscription lowest + possible grain. Required. + :paramtype name: str + """ + super().__init__(**kwargs) self.type = type self.name = name -class ReportConfigSorting(msrest.serialization.Model): +class ReportConfigSorting(_serialization.Model): """The order by expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param direction: Direction of sort. Possible values include: "Ascending", "Descending". - :type direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingDirection - :param name: Required. The name of the column to sort. - :type name: str + :ivar direction: Direction of sort. Known values are: "Ascending" and "Descending". + :vartype direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingType + :ivar name: The name of the column to sort. Required. + :vartype name: str """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'direction': {'key': 'direction', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "direction": {"key": "direction", "type": "str"}, + "name": {"key": "name", "type": "str"}, } def __init__( - self, - *, - name: str, - direction: Optional[Union[str, "ReportConfigSortingDirection"]] = None, - **kwargs + self, *, name: str, direction: Optional[Union[str, "_models.ReportConfigSortingType"]] = None, **kwargs ): - super(ReportConfigSorting, self).__init__(**kwargs) + """ + :keyword direction: Direction of sort. Known values are: "Ascending" and "Descending". + :paramtype direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingType + :keyword name: The name of the column to sort. Required. + :paramtype name: str + """ + super().__init__(**kwargs) self.direction = direction self.name = name -class ReportConfigTimePeriod(msrest.serialization.Model): +class ReportConfigTimePeriod(_serialization.Model): """The start and end date for pulling data for the report. All required parameters must be populated in order to send to Azure. - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime + :ivar from_property: The start date to pull data from. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date to pull data to. Required. + :vartype to: ~datetime.datetime """ _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, + "from_property": {"required": True}, + "to": {"required": True}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - *, - from_property: datetime.datetime, - to: datetime.datetime, - **kwargs - ): - super(ReportConfigTimePeriod, self).__init__(**kwargs) + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, + } + + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date to pull data from. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date to pull data to. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) self.from_property = from_property self.to = to -class Setting(ProxySettingResource): - """State of the myscope setting. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str - :ivar type: Resource type. - :vartype type: str - :param scope: Sets the default scope the current user will see when they sign into Azure Cost - Management in the Azure portal. - :type scope: str - :param start_on: Indicates what scope Cost Management in the Azure portal should default to. - Allowed values: LastUsed. Possible values include: "LastUsed", "ScopePicker", "SpecificScope". - :type start_on: str or ~azure.mgmt.costmanagement.models.SettingsPropertiesStartOn - :param cache: Array of scopes with additional details used by Cost Management in the Azure - portal. - :type cache: list[~azure.mgmt.costmanagement.models.CacheItem] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'start_on': {'key': 'properties.startOn', 'type': 'str'}, - 'cache': {'key': 'properties.cache', 'type': '[CacheItem]'}, - } - - def __init__( - self, - *, - scope: Optional[str] = None, - start_on: Optional[Union[str, "SettingsPropertiesStartOn"]] = None, - cache: Optional[List["CacheItem"]] = None, - **kwargs - ): - super(Setting, self).__init__(**kwargs) - self.scope = scope - self.start_on = start_on - self.cache = cache - - -class SettingsListResult(msrest.serialization.Model): - """Result of listing settings. It contains a list of available settings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of settings. - :vartype value: list[~azure.mgmt.costmanagement.models.Setting] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True, 'max_items': 10, 'min_items': 0}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Setting]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SettingsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class Status(msrest.serialization.Model): +class Status(_serialization.Model): """The status of the long running operation. - :param status: The status of the long running operation. Possible values include: "Running", - "Completed", "Failed". - :type status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :ivar status: The status of the long running operation. Known values are: "InProgress", + "Completed", "Failed", "Queued", "NoDataFound", "ReadyToDownload", and "TimedOut". + :vartype status: str or ~azure.mgmt.costmanagement.models.ReportOperationStatusType """ _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, } - def __init__( - self, - *, - status: Optional[Union[str, "OperationStatusType"]] = None, - **kwargs - ): - super(Status, self).__init__(**kwargs) + def __init__(self, *, status: Optional[Union[str, "_models.ReportOperationStatusType"]] = None, **kwargs): + """ + :keyword status: The status of the long running operation. Known values are: "InProgress", + "Completed", "Failed", "Queued", "NoDataFound", "ReadyToDownload", and "TimedOut". + :paramtype status: str or ~azure.mgmt.costmanagement.models.ReportOperationStatusType + """ + super().__init__(**kwargs) self.status = status -class View(ProxyResource): +class View(ProxyResource): # pylint: disable=too-many-instance-attributes """States and configurations of Cost Analysis. Variables are only populated by the server, and will be ignored when sending a request. @@ -2291,12 +3483,12 @@ class View(ProxyResource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param display_name: User input name of the view. Required. - :type display_name: str - :param scope: Cost Management scope to save the view on. This includes + :vartype e_tag: str + :ivar display_name: User input name of the view. Required. + :vartype display_name: str + :ivar scope: Cost Management scope to save the view on. This includes 'subscriptions/{subscriptionId}' for subscription scope, 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, @@ -2313,76 +3505,74 @@ class View(ProxyResource): ExternalBillingAccount scope, and '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for ExternalSubscription scope. - :type scope: str + :vartype scope: str :ivar created_on: Date the user created this view. :vartype created_on: ~datetime.datetime :ivar modified_on: Date when the user last modified this view. :vartype modified_on: ~datetime.datetime - :ivar date_range: Selected date range for viewing cost in. + :ivar date_range: Date range of the current view. :vartype date_range: str - :ivar currency: Selected currency. + :ivar currency: Currency of the current view. :vartype currency: str - :param chart: Chart type of the main view in Cost Analysis. Required. Possible values include: - "Area", "Line", "StackedColumn", "GroupedColumn", "Table". - :type chart: str or ~azure.mgmt.costmanagement.models.ChartType - :param accumulated: Show costs accumulated over time. Possible values include: "true", "false". - :type accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType - :param metric: Metric to use when displaying costs. Possible values include: "ActualCost", - "AmortizedCost", "AHUB". - :type metric: str or ~azure.mgmt.costmanagement.models.MetricType - :param kpis: List of KPIs to show in Cost Analysis UI. - :type kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] - :param pivots: Configuration of 3 sub-views in the Cost Analysis UI. - :type pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] - :param type_properties_query_type: The type of the report. Usage represents actual usage, + :ivar chart: Chart type of the main view in Cost Analysis. Required. Known values are: "Area", + "Line", "StackedColumn", "GroupedColumn", and "Table". + :vartype chart: str or ~azure.mgmt.costmanagement.models.ChartType + :ivar accumulated: Show costs accumulated over time. Known values are: "true" and "false". + :vartype accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType + :ivar metric: Metric to use when displaying costs. Known values are: "ActualCost", + "AmortizedCost", and "AHUB". + :vartype metric: str or ~azure.mgmt.costmanagement.models.MetricType + :ivar kpis: List of KPIs to show in Cost Analysis UI. + :vartype kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] + :ivar pivots: Configuration of 3 sub-views in the Cost Analysis UI. + :vartype pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] + :ivar type_properties_query_type: The type of the report. Usage represents actual usage, forecast represents forecasted data and UsageAndForecast represents both usage and forecasted - data. Actual usage and forecasted data can be differentiated based on dates. Possible values - include: "Usage". - :type type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType - :param timeframe: The time frame for pulling data for the report. If custom, then a specific - time period must be provided. Possible values include: "WeekToDate", "MonthToDate", - "YearToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType - :param time_period: Has time period for pulling data for the report. - :type time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod - :param data_set: Has definition for data in this report config. - :type data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset - :ivar include_monetary_commitment: Include monetary commitment. + data. Actual usage and forecasted data can be differentiated based on dates. "Usage" + :vartype type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType + :ivar timeframe: The time frame for pulling data for the report. If custom, then a specific + time period must be provided. Known values are: "WeekToDate", "MonthToDate", "YearToDate", and + "Custom". + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType + :ivar time_period: Has time period for pulling data for the report. + :vartype time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod + :ivar data_set: Has definition for data in this report config. + :vartype data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset + :ivar include_monetary_commitment: If true, report includes monetary commitment. :vartype include_monetary_commitment: bool """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'created_on': {'readonly': True}, - 'modified_on': {'readonly': True}, - 'date_range': {'readonly': True}, - 'currency': {'readonly': True}, - 'include_monetary_commitment': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'modified_on': {'key': 'properties.modifiedOn', 'type': 'iso-8601'}, - 'date_range': {'key': 'properties.dateRange', 'type': 'str'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'chart': {'key': 'properties.chart', 'type': 'str'}, - 'accumulated': {'key': 'properties.accumulated', 'type': 'str'}, - 'metric': {'key': 'properties.metric', 'type': 'str'}, - 'kpis': {'key': 'properties.kpis', 'type': '[KpiProperties]'}, - 'pivots': {'key': 'properties.pivots', 'type': '[PivotProperties]'}, - 'type_properties_query_type': {'key': 'properties.query.type', 'type': 'str'}, - 'timeframe': {'key': 'properties.query.timeframe', 'type': 'str'}, - 'time_period': {'key': 'properties.query.timePeriod', 'type': 'ReportConfigTimePeriod'}, - 'data_set': {'key': 'properties.query.dataSet', 'type': 'ReportConfigDataset'}, - 'include_monetary_commitment': {'key': 'properties.query.includeMonetaryCommitment', 'type': 'bool'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "created_on": {"readonly": True}, + "modified_on": {"readonly": True}, + "date_range": {"readonly": True}, + "currency": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "modified_on": {"key": "properties.modifiedOn", "type": "iso-8601"}, + "date_range": {"key": "properties.dateRange", "type": "str"}, + "currency": {"key": "properties.currency", "type": "str"}, + "chart": {"key": "properties.chart", "type": "str"}, + "accumulated": {"key": "properties.accumulated", "type": "str"}, + "metric": {"key": "properties.metric", "type": "str"}, + "kpis": {"key": "properties.kpis", "type": "[KpiProperties]"}, + "pivots": {"key": "properties.pivots", "type": "[PivotProperties]"}, + "type_properties_query_type": {"key": "properties.query.type", "type": "str"}, + "timeframe": {"key": "properties.query.timeframe", "type": "str"}, + "time_period": {"key": "properties.query.timePeriod", "type": "ReportConfigTimePeriod"}, + "data_set": {"key": "properties.query.dataSet", "type": "ReportConfigDataset"}, + "include_monetary_commitment": {"key": "properties.query.includeMonetaryCommitment", "type": "bool"}, } def __init__( @@ -2391,18 +3581,70 @@ def __init__( e_tag: Optional[str] = None, display_name: Optional[str] = None, scope: Optional[str] = None, - chart: Optional[Union[str, "ChartType"]] = None, - accumulated: Optional[Union[str, "AccumulatedType"]] = None, - metric: Optional[Union[str, "MetricType"]] = None, - kpis: Optional[List["KpiProperties"]] = None, - pivots: Optional[List["PivotProperties"]] = None, - type_properties_query_type: Optional[Union[str, "ReportType"]] = None, - timeframe: Optional[Union[str, "ReportTimeframeType"]] = None, - time_period: Optional["ReportConfigTimePeriod"] = None, - data_set: Optional["ReportConfigDataset"] = None, + chart: Optional[Union[str, "_models.ChartType"]] = None, + accumulated: Optional[Union[str, "_models.AccumulatedType"]] = None, + metric: Optional[Union[str, "_models.MetricType"]] = None, + kpis: Optional[List["_models.KpiProperties"]] = None, + pivots: Optional[List["_models.PivotProperties"]] = None, + type_properties_query_type: Optional[Union[str, "_models.ReportType"]] = None, + timeframe: Optional[Union[str, "_models.ReportTimeframeType"]] = None, + time_period: Optional["_models.ReportConfigTimePeriod"] = None, + data_set: Optional["_models.ReportConfigDataset"] = None, + include_monetary_commitment: Optional[bool] = None, **kwargs ): - super(View, self).__init__(e_tag=e_tag, **kwargs) + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword display_name: User input name of the view. Required. + :paramtype display_name: str + :keyword scope: Cost Management scope to save the view on. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + '/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + ExternalBillingAccount scope, and + '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + ExternalSubscription scope. + :paramtype scope: str + :keyword chart: Chart type of the main view in Cost Analysis. Required. Known values are: + "Area", "Line", "StackedColumn", "GroupedColumn", and "Table". + :paramtype chart: str or ~azure.mgmt.costmanagement.models.ChartType + :keyword accumulated: Show costs accumulated over time. Known values are: "true" and "false". + :paramtype accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType + :keyword metric: Metric to use when displaying costs. Known values are: "ActualCost", + "AmortizedCost", and "AHUB". + :paramtype metric: str or ~azure.mgmt.costmanagement.models.MetricType + :keyword kpis: List of KPIs to show in Cost Analysis UI. + :paramtype kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] + :keyword pivots: Configuration of 3 sub-views in the Cost Analysis UI. + :paramtype pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] + :keyword type_properties_query_type: The type of the report. Usage represents actual usage, + forecast represents forecasted data and UsageAndForecast represents both usage and forecasted + data. Actual usage and forecasted data can be differentiated based on dates. "Usage" + :paramtype type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType + :keyword timeframe: The time frame for pulling data for the report. If custom, then a specific + time period must be provided. Known values are: "WeekToDate", "MonthToDate", "YearToDate", and + "Custom". + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType + :keyword time_period: Has time period for pulling data for the report. + :paramtype time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod + :keyword data_set: Has definition for data in this report config. + :paramtype data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset + :keyword include_monetary_commitment: If true, report includes monetary commitment. + :paramtype include_monetary_commitment: bool + """ + super().__init__(e_tag=e_tag, **kwargs) self.display_name = display_name self.scope = scope self.created_on = None @@ -2418,10 +3660,10 @@ def __init__( self.timeframe = timeframe self.time_period = time_period self.data_set = data_set - self.include_monetary_commitment = None + self.include_monetary_commitment = include_monetary_commitment -class ViewListResult(msrest.serialization.Model): +class ViewListResult(_serialization.Model): """Result of listing views. It contains a list of available views. Variables are only populated by the server, and will be ignored when sending a request. @@ -2433,19 +3675,17 @@ class ViewListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[View]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[View]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ViewListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py index c70a4cb564cb..56106cebd774 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._settings_operations import SettingsOperations +from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations from ._views_operations import ViewsOperations from ._alerts_operations import AlertsOperations from ._forecast_operations import ForecastOperations @@ -15,15 +15,31 @@ from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations from ._operations import Operations from ._exports_operations import ExportsOperations +from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations +from ._generate_detailed_cost_report_operation_results_operations import ( + GenerateDetailedCostReportOperationResultsOperations, +) +from ._generate_detailed_cost_report_operation_status_operations import ( + GenerateDetailedCostReportOperationStatusOperations, +) + +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__ = [ - 'SettingsOperations', - 'ViewsOperations', - 'AlertsOperations', - 'ForecastOperations', - 'DimensionsOperations', - 'QueryOperations', - 'GenerateReservationDetailsReportOperations', - 'Operations', - 'ExportsOperations', + "GenerateCostDetailsReportOperations", + "ViewsOperations", + "AlertsOperations", + "ForecastOperations", + "DimensionsOperations", + "QueryOperations", + "GenerateReservationDetailsReportOperations", + "Operations", + "ExportsOperations", + "GenerateDetailedCostReportOperations", + "GenerateDetailedCostReportOperationResultsOperations", + "GenerateDetailedCostReportOperationStatusOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py index 13969e75db88..6eb7175b3414 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,51 +6,166 @@ # 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 TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +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(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/alerts") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _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_get_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _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_dismiss_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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", "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + # 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") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -class AlertsOperations(object): - """AlertsOperations 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. +def build_list_external_request( + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_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) + + +class AlertsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`alerts` 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 list( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AlertsResult" + @distributed_trace + def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: """Lists the alerts for scope defined. :param scope: The scope associated with alerts operations. This includes @@ -67,60 +183,59 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_list_request( + scope=scope, + 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) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts'} # type: ignore - def get( - self, - scope, # type: str - alert_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Alert" + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts"} # type: ignore + + @distributed_trace + def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: """Gets the alert for the scope by alert ID. :param scope: The scope associated with alerts operations. This includes @@ -138,64 +253,70 @@ def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @overload def dismiss( self, - scope, # type: str - alert_id, # type: str - parameters, # type: "_models.DismissAlertPayload" - **kwargs # type: Any - ): - # type: (...) -> "_models.Alert" + scope: str, + alert_id: str, + parameters: _models.DismissAlertPayload, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Alert: """Dismisses the specified alert. :param scope: The scope associated with alerts operations. This includes @@ -213,121 +334,215 @@ def dismiss( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str - :param parameters: Parameters supplied to the Dismiss Alert operation. + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def dismiss( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def dismiss( + self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO], **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.dismiss.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'DismissAlertPayload') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.Alert] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "DismissAlertPayload") + + request = build_dismiss_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.dismiss.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - dismiss.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + dismiss.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @distributed_trace def list_external( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AlertsResult" + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + **kwargs: Any + ) -> _models.AlertsResult: """Lists the Alerts for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list_external.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] + + request = build_list_external_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + template_url=self.list_external.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 + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_external.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts'} # type: ignore + + list_external.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py index ff843ebbf69e..73dbfbd8b843 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,56 +6,151 @@ # 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 TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union -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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class DimensionsOperations(object): - """DimensionsOperations 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. +def build_list_request( + scope: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/dimensions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_by_external_cloud_provider_type_request( + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DimensionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`dimensions` 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, - scope, # type: str - filter=None, # type: Optional[str] - expand=None, # type: Optional[str] - skiptoken=None, # type: Optional[str] - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DimensionsListResult"] + scope: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> Iterable["_models.Dimension"]: """Lists the dimensions by the defined scope. :param scope: The scope associated with dimension operations. This includes @@ -72,66 +168,68 @@ def list( 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + 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) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -140,100 +238,106 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/dimensions'} # type: ignore + return ItemPaged(get_next, extract_data) + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/dimensions"} # type: ignore + + @distributed_trace def by_external_cloud_provider_type( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - filter=None, # type: Optional[str] - expand=None, # type: Optional[str] - skiptoken=None, # type: Optional[str] - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DimensionsListResult"] + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> Iterable["_models.Dimension"]: """Lists the dimensions by the external cloud provider type. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -242,17 +346,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions'} # type: ignore + return ItemPaged(get_next, extract_data) + + by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py index 89eefe5166d4..9c193555c2fe 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,54 +6,214 @@ # 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 TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +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(scope: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, export_name: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ExportsOperations(object): - """ExportsOperations operations. + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - 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.costmanagement.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. +def build_execute_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "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_get_execution_history_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "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) + + +class ExportsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`exports` 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 list( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.ExportListResult" + @distributed_trace + def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _models.ExportListResult: """The operation to list all exports at the given scope. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -67,63 +228,67 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last execution of each export. + Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportListResult, or the result of cls(response) + :return: ExportListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportListResult] + + request = build_list_request( + scope=scope, + expand=expand, + 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) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportListResult', pipeline_response) + deserialized = self._deserialize("ExportListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports'} # type: ignore - def get( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Export" + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports"} # type: ignore + + @distributed_trace + def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.Export: """The operation to get the export for the defined scope by export name. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -138,69 +303,80 @@ def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last 10 executions of the export. + Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Export] + + request = build_get_request( + scope=scope, + export_name=export_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @overload def create_or_update( self, - scope, # type: str - export_name, # type: str - parameters, # type: "_models.Export" - **kwargs # type: Any - ): - # type: (...) -> "_models.Export" + scope: str, + export_name: str, + parameters: _models.Export, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Export: """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -215,77 +391,165 @@ def create_or_update( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str - :param parameters: Parameters supplied to the CreateOrUpdate Export operation. + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.Export + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, scope: str, export_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, scope: str, export_name: str, parameters: Union[_models.Export, IO], **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Export or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] 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 = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Export') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.Export] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Export") + + request = build_create_or_update_request( + scope=scope, + export_name=export_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore - def delete( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any + ) -> None: """The operation to delete a export. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -300,63 +564,63 @@ def delete( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore - def execute( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - """The operation to execute a export. - - :param scope: The scope associated with query and export operations. This includes + @distributed_trace + def execute( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any + ) -> None: + """The operation to execute an export. + + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -371,63 +635,61 @@ def execute( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.execute.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_execute_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.execute.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - execute.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run'} # type: ignore + execute.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run"} # type: ignore - def get_execution_history( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.ExportExecutionListResult" - """The operation to get the execution history of an export for the defined scope by export name. - - :param scope: The scope associated with query and export operations. This includes + @distributed_trace + def get_execution_history(self, scope: str, export_name: str, **kwargs: Any) -> _models.ExportExecutionListResult: + """The operation to get the execution history of an export for the defined scope and export name. + + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -442,52 +704,56 @@ def get_execution_history( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportExecutionListResult, or the result of cls(response) + :return: ExportExecutionListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportExecutionListResult"] 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_execution_history.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportExecutionListResult] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_execution_history_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.get_execution_history.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 + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportExecutionListResult', pipeline_response) + deserialized = self._deserialize("ExportExecutionListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_execution_history.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory'} # type: ignore + + get_execution_history.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py index 71c2e338e1e5..1c40fa8c9cd3 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,53 +6,133 @@ # 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 TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class ForecastOperations(object): - """ForecastOperations 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. +def build_usage_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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", "/{scope}/providers/Microsoft.CostManagement/forecast") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_external_cloud_provider_usage_request( + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ForecastOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`forecast` 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") + @overload def usage( self, - scope, # type: str - parameters, # type: "_models.ForecastDefinition" - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.QueryResult"] + scope: str, + parameters: _models.ForecastDefinition, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.ForecastResult]: """Lists the forecast charges for scope defined. :param scope: The scope associated with forecast operations. This includes @@ -69,141 +150,334 @@ def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: 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: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def usage( + self, + scope: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def usage( + self, scope: str, parameters: Union[_models.ForecastDefinition, IO], filter: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.ForecastResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_usage_request( + scope=scope, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.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, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/forecast'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/forecast"} # type: ignore + + @overload def external_cloud_provider_usage( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - parameters, # type: "_models.ForecastDefinition" - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.QueryResult" + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: _models.ForecastDefinition, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ForecastResult: """Lists the forecast charges for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: 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: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: Union[_models.ForecastDefinition, IO], + filter: Optional[str] = None, + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.external_cloud_provider_usage.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.ForecastResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_external_cloud_provider_usage_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.external_cloud_provider_usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - external_cloud_provider_usage.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast'} # type: ignore + + external_cloud_provider_usage.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py new file mode 100644 index 000000000000..3227e57e51cc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py @@ -0,0 +1,510 @@ +# 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, 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 .._serialization import Serializer +from .._vendor import _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_create_operation_request(scope: 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-05-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", "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _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) + + +def build_get_operation_results_request(scope: str, operation_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-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateCostDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_cost_details_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + 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-05-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.CostDetailsOperationResults]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateCostDetailsReportRequestDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateCostDetailsReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if response.status_code == 202: + 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 + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + @overload + def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateCostDetailsReportRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :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-05-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.CostDetailsOperationResults] + 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_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + def _get_operation_results_initial( + self, scope: str, operation_id: str, **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + 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-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CostDetailsOperationResults]] + + request = build_get_operation_results_request( + scope=scope, + operation_id=operation_id, + api_version=api_version, + template_url=self._get_operation_results_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _get_operation_results_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore + + @distributed_trace + def begin_get_operation_results( + self, scope: str, operation_id: str, **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """Get the result of the specified operation. This link is provided in the CostDetails creation + request response Location header. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param operation_id: The target operation Id. Required. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CostDetailsOperationResults] + 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._get_operation_results_initial( # type: ignore + scope=scope, + operation_id=operation_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_get_operation_results.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py new file mode 100644 index 000000000000..3e05423a707a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py @@ -0,0 +1,154 @@ +# 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, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +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(operation_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}") + path_format_arguments = { + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateDetailedCostReportOperationResultsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_results` 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") + + @distributed_trace + def get( + self, operation_id: str, scope: str, **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + """Get the result of the specified operation. This link is provided in the + GenerateDetailedCostReport creation request response header. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GenerateDetailedCostReportOperationResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult or 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", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py new file mode 100644 index 000000000000..646d9d52c76c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py @@ -0,0 +1,150 @@ +# 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, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +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(operation_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}") + path_format_arguments = { + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateDetailedCostReportOperationStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_status` 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") + + @distributed_trace + def get(self, operation_id: str, scope: str, **kwargs: Any) -> _models.GenerateDetailedCostReportOperationStatuses: + """Get the status of the specified operation. This link is provided in the + GenerateDetailedCostReport creation request response header. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GenerateDetailedCostReportOperationStatuses or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationStatuses + :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", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationStatuses] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py new file mode 100644 index 000000000000..9f88c1dd6b03 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py @@ -0,0 +1,341 @@ +# 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, 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 .._serialization import Serializer +from .._vendor import _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_create_operation_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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", "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _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 GenerateDetailedCostReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_detailed_cost_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + 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", "2021-10-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.GenerateDetailedCostReportOperationResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateDetailedCostReportDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateDetailedCostReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Azure-Consumption-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-Consumption-AsyncOperation") + ) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore + + @overload + def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateDetailedCostReportDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(Only enterprise + customers) or Invoice Id asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 GenerateDetailedCostReportOperationResult + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(Only enterprise + customers) or Invoice Id asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(Only enterprise + customers) or Invoice Id asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 GenerateDetailedCostReportOperationResult + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.GenerateDetailedCostReportOperationResult] + 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_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py index 4c93c64e8755..efac755a9350 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,306 +6,378 @@ # 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 TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_by_billing_account_id_request( + billing_account_id: str, *, start_date: str, end_date: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +def build_by_billing_profile_id_request( + billing_account_id: str, billing_profile_id: str, *, start_date: str, end_date: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") -class GenerateReservationDetailsReportOperations(object): - """GenerateReservationDetailsReportOperations operations. + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), + } - 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. + _url = _format_url_section(_url, **path_format_arguments) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. + # Construct parameters + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateReservationDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_reservation_details_report` 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 _by_billing_account_id_initial( - self, - billing_account_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.OperationStatus"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_account_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_account_id_request( + billing_account_id=billing_account_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_account_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + 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 - _by_billing_account_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_account_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace def begin_by_billing_account_id( - self, - billing_account_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.OperationStatus"] + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously based on - enrollment id. + enrollment id. The Reservation usage details can be viewed only by certain enterprise roles. + For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. - :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). + :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). Required. :type billing_account_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :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. + :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 OperationStatus or the result of cls(response) + :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 OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + 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._by_billing_account_id_initial( + raw_result = self._by_billing_account_id_initial( # type: ignore billing_account_id=billing_account_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_account_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_account_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore def _by_billing_profile_id_initial( - self, - billing_account_id, # type: str - billing_profile_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.OperationStatus"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_profile_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_profile_id_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_profile_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + 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 - _by_billing_profile_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_profile_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace def begin_by_billing_profile_id( - self, - billing_account_id, # type: str - billing_profile_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.OperationStatus"] + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously by billing - profile. + profile. The Reservation usage details can be viewed by only certain enterprise roles by + default. For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: BillingProfile ID. + :param billing_profile_id: BillingProfile ID. Required. :type billing_profile_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :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. + :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 OperationStatus or the result of cls(response) + :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 OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + 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._by_billing_profile_id_initial( + raw_result = self._by_billing_profile_id_initial( # type: ignore billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_profile_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_profile_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py index 4a538a66f2c5..f3a97201f95a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,117 @@ # 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 TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +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 HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") -class Operations(object): - """Operations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/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. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationListResult"] + 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.Operation"]: """Lists all of the available cost management REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +125,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/operations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.CostManagement/operations"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/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/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py index b5dd2dc857ec..1086b2739734 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,52 +6,121 @@ # 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 TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class QueryOperations(object): - """QueryOperations 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. +def build_usage_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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", "/{scope}/providers/Microsoft.CostManagement/query") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _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) + + +def build_usage_by_external_cloud_provider_type_request( + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_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 QueryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`query` 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") + @overload def usage( - self, - scope, # type: str - parameters, # type: "_models.QueryDefinition" - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.QueryResult"] + self, scope: str, parameters: _models.QueryDefinition, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: """Query the usage data for scope defined. :param scope: The scope associated with query and export operations. This includes @@ -68,128 +138,295 @@ def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def usage( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def usage( + self, scope: str, parameters: Union[_models.QueryDefinition, IO], **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: QueryResult, or the result of cls(response) + :return: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] 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 = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.QueryResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.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, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/query'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/query"} # type: ignore + + @overload def usage_by_external_cloud_provider_type( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - parameters, # type: "_models.QueryDefinition" - **kwargs # type: Any - ): - # type: (...) -> "_models.QueryResult" + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: _models.QueryDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.QueryResult: """Query the usage data for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) + :return: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_id: str, + parameters: Union[_models.QueryDefinition, IO], + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage_by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.QueryResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage_by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage_by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query'} # type: ignore + + usage_by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py deleted file mode 100644 index 3140937a8c4c..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py +++ /dev/null @@ -1,281 +0,0 @@ -# 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 TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class SettingsOperations(object): - """SettingsOperations 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.costmanagement.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. - """ - - models = _models - - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.SettingsListResult"] - """Lists all of the settings that have been customized. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SettingsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.SettingsListResult] - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SettingsListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) - return request - - def extract_data(pipeline_response): - deserialized = self._deserialize('SettingsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/settings'} # type: ignore - - def get( - self, - setting_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Setting" - """Retrieves the current value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - def create_or_update( - self, - setting_name, # type: str - parameters, # type: "_models.Setting" - **kwargs # type: Any - ): - # type: (...) -> "_models.Setting" - """Sets a new value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :param parameters: Body supplied to the CreateOrUpdate setting operation. - :type parameters: ~azure.mgmt.costmanagement.models.Setting - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Setting') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - def delete( - self, - setting_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - """Remove the current value for a specific setting and reverts back to the default value, if - applicable. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py index d7512a2a7003..880ae59adf4f 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,294 @@ # 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 TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +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: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/views") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/views") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "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_get_request(view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "viewName": _SERIALIZER.url("view_name", view_name, "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_create_or_update_request(view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.CostManagement/views/{viewName}") + path_format_arguments = { + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class ViewsOperations(object): - """ViewsOperations 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. +def build_create_or_update_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.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. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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", "/{scope}/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ViewsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`views` 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 list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ViewListResult"] + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.View"]: """Lists all views by tenant and object. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,27 +302,24 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/views'} # type: ignore + return ItemPaged(get_next, extract_data) - def list_by_scope( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ViewListResult"] + list.metadata = {"url": "/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace + def list_by_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.View"]: """Lists all views at the given scope. :param scope: The scope associated with view operations. This includes @@ -133,46 +338,49 @@ def list_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + 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 = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -181,204 +389,251 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views'} # type: ignore + return ItemPaged(get_next, extract_data) - def get( - self, - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace + def get(self, view_name: str, **kwargs: Any) -> _models.View: """Gets the view by view name. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + view_name=view_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload def create_or_update( - self, - view_name, # type: str - parameters, # type: "_models.View" - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + self, view_name: str, parameters: _models.View, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update(self, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_request( + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - def delete( - self, - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace + def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """The operation to delete a view. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_delete_request( + view_name=view_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore - def get_by_scope( - self, - scope, # type: str - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + @distributed_trace + def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.View: """Gets the view for the defined scope by view name. :param scope: The scope associated with view operations. This includes @@ -397,64 +652,70 @@ def get_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] 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 = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.get_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload def create_or_update_by_scope( self, - scope, # type: str - view_name, # type: str - parameters, # type: "_models.View" - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + scope: str, + view_name: str, + parameters: _models.View, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -475,74 +736,164 @@ def create_or_update_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] 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 = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-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.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - def delete_by_scope( - self, - scope, # type: str - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace + def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, view_name: str, **kwargs: Any + ) -> None: """The operation to delete a view. :param scope: The scope associated with view operations. This includes @@ -561,49 +912,52 @@ def delete_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.delete_by_scope.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 + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore