From 96304f4d6217110c7ae60b5f65326ab644e99164 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Fri, 2 Dec 2022 01:28:32 +0000 Subject: [PATCH] CodeGen from PR 21677 in Azure/azure-rest-api-specs Fix s360 in reservation and scheduled action APIs (#21677) * Fix s360 in reservation and scheduled action APIs * Fix lint errors * Fix linter error in RI recommendation example * Fix lint errors * Review comment - changed suppression rule name --- .../azure-mgmt-consumption/_meta.json | 12 +- .../azure/mgmt/consumption/__init__.py | 7 +- .../azure/mgmt/consumption/_configuration.py | 51 +- .../_consumption_management_client.py | 104 +- .../azure/mgmt/consumption/_patch.py | 2 +- .../azure/mgmt/consumption/_serialization.py | 1967 ++++++++ .../azure/mgmt/consumption/_vendor.py | 6 +- .../azure/mgmt/consumption/_version.py | 2 +- .../azure/mgmt/consumption/aio/__init__.py | 7 +- .../mgmt/consumption/aio/_configuration.py | 50 +- .../aio/_consumption_management_client.py | 95 +- .../azure/mgmt/consumption/aio/_patch.py | 2 +- .../consumption/aio/operations/__init__.py | 39 +- .../operations/_aggregated_cost_operations.py | 114 +- .../aio/operations/_balances_operations.py | 113 +- .../aio/operations/_budgets_operations.py | 320 +- .../aio/operations/_charges_operations.py | 57 +- .../aio/operations/_credits_operations.py | 64 +- .../aio/operations/_events_operations.py | 183 +- .../aio/operations/_lots_operations.py | 252 +- .../operations/_marketplaces_operations.py | 92 +- .../consumption/aio/operations/_operations.py | 85 +- .../mgmt/consumption/aio/operations/_patch.py | 1 + .../aio/operations/_price_sheet_operations.py | 103 +- ...ation_recommendation_details_operations.py | 73 +- ..._reservation_recommendations_operations.py | 94 +- .../_reservation_transactions_operations.py | 201 +- .../_reservations_details_operations.py | 268 +- .../_reservations_summaries_operations.py | 256 +- .../aio/operations/_tags_operations.py | 61 +- .../operations/_usage_details_operations.py | 98 +- .../azure/mgmt/consumption/models/__init__.py | 234 +- .../_consumption_management_client_enums.py | 90 +- .../mgmt/consumption/models/_models_py3.py | 4317 +++++++++-------- .../azure/mgmt/consumption/models/_patch.py | 1 + .../mgmt/consumption/operations/__init__.py | 39 +- .../operations/_aggregated_cost_operations.py | 176 +- .../operations/_balances_operations.py | 173 +- .../operations/_budgets_operations.py | 454 +- .../operations/_charges_operations.py | 89 +- .../operations/_credits_operations.py | 103 +- .../operations/_events_operations.py | 254 +- .../operations/_lots_operations.py | 350 +- .../operations/_marketplaces_operations.py | 123 +- .../consumption/operations/_operations.py | 110 +- .../mgmt/consumption/operations/_patch.py | 1 + .../operations/_price_sheet_operations.py | 176 +- ...ation_recommendation_details_operations.py | 119 +- ..._reservation_recommendations_operations.py | 130 +- .../_reservation_transactions_operations.py | 277 +- .../_reservations_details_operations.py | 370 +- .../_reservations_summaries_operations.py | 361 +- .../operations/_tags_operations.py | 90 +- .../operations/_usage_details_operations.py | 135 +- .../aggregated_cost_by_management_group.py | 40 + ...cost_by_management_group_filter_by_date.py | 40 + ..._for_billing_period_by_management_group.py | 41 + .../balances_by_billing_account.py | 40 + ...s_by_billing_account_for_billing_period.py | 41 + .../generated_samples/budget.py | 41 + .../generated_samples/budgets_list.py | 41 + ...harges_for_billing_period_by_department.py | 40 + ...or_billing_period_by_enrollment_account.py | 40 + .../charges_list_by_modern_billing_account.py | 40 + ...ing_account_group_by_billing_profile_id.py | 40 + ...rn_billing_account_group_by_customer_id.py | 40 + ...ing_account_group_by_invoice_section_id.py | 40 + .../charges_list_by_modern_billing_profile.py | 40 + ...ing_profile_group_by_invoice_section_id.py | 40 + ..._modern_billing_profile_invoice_section.py | 40 + .../charges_list_by_modern_customer.py | 40 + ...arges_list_by_modern_invoice_section_id.py | 40 + ...for_department_filter_by_start_end_date.py | 40 + ...llment_account_filter_by_start_end_date.py | 40 + .../create_or_update_budget.py | 80 + .../credit_summary_by_billing_profile.py | 41 + .../generated_samples/delete_budget.py | 41 + .../events_get_by_billing_account.py | 41 + ...nts_get_by_billing_account_with_filters.py | 41 + .../events_list_by_billing_profile.py | 44 + .../lots_list_by_billing_account.py | 41 + ...ts_list_by_billing_account_with_filters.py | 41 + .../lots_list_by_billing_profile.py | 42 + .../lots_list_by_customer.py | 42 + .../lots_list_by_customer_with_filters.py | 42 + .../marketplaces_by_billing_account_list.py | 41 + ...billing_account_list_for_billing_period.py | 41 + .../marketplaces_by_department_list.py | 41 + ...es_by_department_list_by_billing_period.py | 41 + ...marketplaces_by_enrollment_account_list.py | 41 + ...ollment_accounts_list_by_billing_period.py | 41 + .../marketplaces_by_management_group_list.py | 41 + ...anagement_group_list_for_billing_period.py | 41 + .../generated_samples/marketplaces_list.py | 41 + .../marketplaces_list_for_billing_period.py | 41 + .../generated_samples/operation_list.py | 39 + .../generated_samples/price_sheet.py | 38 + .../generated_samples/price_sheet_expand.py | 40 + .../price_sheet_for_billing_period.py | 40 + .../generated_samples/reservation_details.py | 42 + ...servation_details_by_billing_account_id.py | 41 + ...servation_details_by_billing_profile_id.py | 41 + ...ls_by_billing_profile_id_reservation_id.py | 41 + ...reservation_details_with_reservation_id.py | 43 + ...commendation_details_by_billing_account.py | 45 + ...commendation_details_by_billing_profile.py | 45 + ...ecommendation_details_by_resource_group.py | 45 + ..._recommendation_details_by_subscription.py | 45 + ...tion_recommendations_by_billing_account.py | 41 + ...tion_recommendations_by_billing_profile.py | 41 + ...ation_recommendations_by_resource_group.py | 41 + ...rvation_recommendations_by_subscription.py | 41 + ...subscription_for_scope_look_back_period.py | 41 + .../reservation_summaries_daily.py | 42 + ...summaries_daily_with_billing_account_id.py | 42 + ...summaries_daily_with_billing_profile_id.py | 42 + ...ion_summaries_daily_with_reservation_id.py | 43 + .../reservation_summaries_monthly.py | 42 + ...mmaries_monthly_with_billing_account_id.py | 42 + ...mmaries_monthly_with_billing_profile_id.py | 42 + ..._with_billing_profile_id_reservation_id.py | 42 + ...n_summaries_monthly_with_reservation_id.py | 43 + ...transactions_list_by_billing_profile_id.py | 42 + ..._transactions_list_by_enrollment_number.py | 41 + .../generated_samples/tags.py | 40 + .../generated_samples/usage_details_expand.py | 41 + .../generated_samples/usage_details_list.py | 41 + .../usage_details_list_by_billing_account.py | 41 + .../usage_details_list_by_department.py | 41 + ...sage_details_list_by_enrollment_account.py | 41 + .../usage_details_list_by_management_group.py | 41 + ...age_details_list_by_mca_billing_account.py | 41 + ...age_details_list_by_mca_billing_profile.py | 41 + .../usage_details_list_by_mca_customer.py | 41 + ...age_details_list_by_mca_invoice_section.py | 41 + ...sage_details_list_by_metric_actual_cost.py | 41 + ...e_details_list_by_metric_amortized_cost.py | 41 + .../usage_details_list_by_metric_usage.py | 41 + .../usage_details_list_filter_by_tag.py | 41 + .../usage_details_list_for_billing_period.py | 41 + ...t_for_billing_period_by_billing_account.py | 41 + ...s_list_for_billing_period_by_department.py | 41 + ...or_billing_period_by_enrollment_account.py | 41 + ..._for_billing_period_by_management_group.py | 41 + 144 files changed, 11525 insertions(+), 5168 deletions(-) create mode 100644 sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py create mode 100644 sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py diff --git a/sdk/consumption/azure-mgmt-consumption/_meta.json b/sdk/consumption/azure-mgmt-consumption/_meta.json index 4782772c1c8bd..a7eb17efd9ee8 100644 --- a/sdk/consumption/azure-mgmt-consumption/_meta.json +++ b/sdk/consumption/azure-mgmt-consumption/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "commit": "83cde4fa7d6c820f574b9aec973fd9597385e312", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.16.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.2.7", + "@autorest/modelerfour@4.24.3" ], - "commit": "c2d25c0f023edd1fea753a89d6409f3e7a9f8956", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/consumption/resource-manager/readme.md --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --use=@autorest/python@5.16.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/consumption/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.2.7 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/consumption/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py index cbf01ba8efbc5..fcba3ab9cc051 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py @@ -13,11 +13,14 @@ try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * # pylint: disable=unused-wildcard-import except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['ConsumptionManagementClient'] + +__all__ = [ + "ConsumptionManagementClient", +] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py index f7117a221edc9..013feb87a864f 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential @@ -25,23 +31,18 @@ class ConsumptionManagementClientConfiguration(Configuration): # pylint: disabl Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: Azure Subscription ID. + :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(ConsumptionManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", "2021-10-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-consumption/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-consumption/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - 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') + 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.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py index fa361d8c6841a..e4acefe4f4184 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py @@ -9,20 +9,38 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from . import models +from . import models as _models from ._configuration import ConsumptionManagementClientConfiguration -from .operations import AggregatedCostOperations, BalancesOperations, BudgetsOperations, ChargesOperations, CreditsOperations, EventsOperations, LotsOperations, MarketplacesOperations, Operations, PriceSheetOperations, ReservationRecommendationDetailsOperations, ReservationRecommendationsOperations, ReservationTransactionsOperations, ReservationsDetailsOperations, ReservationsSummariesOperations, TagsOperations, UsageDetailsOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + AggregatedCostOperations, + BalancesOperations, + BudgetsOperations, + ChargesOperations, + CreditsOperations, + EventsOperations, + LotsOperations, + MarketplacesOperations, + Operations, + PriceSheetOperations, + ReservationRecommendationDetailsOperations, + ReservationRecommendationsOperations, + ReservationTransactionsOperations, + ReservationsDetailsOperations, + ReservationsSummariesOperations, + TagsOperations, + UsageDetailsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class ConsumptionManagementClient: # pylint: disable=too-many-instance-attributes + +class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Consumption management client provides access to consumption resources for Azure Enterprise Subscriptions. @@ -64,9 +82,9 @@ class ConsumptionManagementClient: # pylint: disable=too-many-instance-attrib :vartype lots: azure.mgmt.consumption.operations.LotsOperations :ivar credits: CreditsOperations operations :vartype credits: azure.mgmt.consumption.operations.CreditsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: Azure Subscription ID. + :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -82,31 +100,21 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = ConsumptionManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = ConsumptionManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.usage_details = UsageDetailsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.marketplaces = MarketplacesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.budgets = BudgetsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.tags = TagsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.charges = ChargesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.balances = BalancesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.usage_details = UsageDetailsOperations(self._client, self._config, self._serialize, self._deserialize) + self.marketplaces = MarketplacesOperations(self._client, self._config, self._serialize, self._deserialize) + self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.tags = TagsOperations(self._client, self._config, self._serialize, self._deserialize) + self.charges = ChargesOperations(self._client, self._config, self._serialize, self._deserialize) + self.balances = BalancesOperations(self._client, self._config, self._serialize, self._deserialize) self.reservations_summaries = ReservationsSummariesOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -122,31 +130,14 @@ def __init__( self.reservation_transactions = ReservationTransactionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.price_sheet = PriceSheetOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize - ) - self.aggregated_cost = AggregatedCostOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.events = EventsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.lots = LotsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.credits = CreditsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.aggregated_cost = AggregatedCostOperations(self._client, self._config, self._serialize, self._deserialize) + self.events = EventsOperations(self._client, self._config, self._serialize, self._deserialize) + self.lots = LotsOperations(self._client, self._config, self._serialize, self._deserialize) + self.credits = CreditsOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -155,7 +146,7 @@ def _send_request( >>> response = client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest @@ -168,15 +159,12 @@ def _send_request( request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> ConsumptionManagementClient + def __enter__(self) -> "ConsumptionManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py new file mode 100644 index 0000000000000..2c170e28dbca2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py @@ -0,0 +1,1967 @@ +# -------------------------------------------------------------------------- +# +# 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 +# pyright: reportUnnecessaryTypeIgnoreComment=false + +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 +from typing import Optional, Union, AnyStr, IO, Mapping + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from typing import Dict, Any, cast + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + + +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: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> 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: Optional[Union[AnyStr, IO]], headers: 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 + unicode_str = str + +_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 # type: ignore +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 +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) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + 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) # type: ignore + 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) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _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 = [ # type: ignore + 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): # type: ignore + # 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) # type: ignore + return result + except ValueError: + for enum_value in enum_obj: # type: ignore + 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 # type: ignore + 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 # type: ignore + 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) # type: ignore + 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) # type: ignore + 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): # type: ignore + 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)) # type: ignore + + @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) # type: ignore + attr = attr + padding # type: ignore + 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) # type: ignore + 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) # type: ignore + + @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): # type: ignore + 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): # type: ignore + 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) # type: ignore + 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() # type: ignore + 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) # type: ignore + 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/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py index 138f663c53a4e..9aad73fc743e7 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py @@ -7,6 +7,7 @@ from azure.core.pipeline.transport import HttpRequest + def _convert_request(request, files=None): data = request.content if not files else None request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) @@ -14,6 +15,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -21,7 +23,5 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py index 9f8bb24bdd995..e5754a47ce68f 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "10.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/__init__.py index 1ecd3246c688e..9cde86302a9bc 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/__init__.py @@ -10,11 +10,14 @@ try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * # pylint: disable=unused-wildcard-import except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['ConsumptionManagementClient'] + +__all__ = [ + "ConsumptionManagementClient", +] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py index ff0354538d38e..92d21cc93087a 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential @@ -25,23 +31,18 @@ class ConsumptionManagementClientConfiguration(Configuration): # pylint: disabl Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: Azure Subscription ID. + :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(ConsumptionManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", "2021-10-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-consumption/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-consumption/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py index 2fa63b6b1bd9c..bbfde391df8d1 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py @@ -9,20 +9,38 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from .. import models +from .. import models as _models +from .._serialization import Deserializer, Serializer from ._configuration import ConsumptionManagementClientConfiguration -from .operations import AggregatedCostOperations, BalancesOperations, BudgetsOperations, ChargesOperations, CreditsOperations, EventsOperations, LotsOperations, MarketplacesOperations, Operations, PriceSheetOperations, ReservationRecommendationDetailsOperations, ReservationRecommendationsOperations, ReservationTransactionsOperations, ReservationsDetailsOperations, ReservationsSummariesOperations, TagsOperations, UsageDetailsOperations +from .operations import ( + AggregatedCostOperations, + BalancesOperations, + BudgetsOperations, + ChargesOperations, + CreditsOperations, + EventsOperations, + LotsOperations, + MarketplacesOperations, + Operations, + PriceSheetOperations, + ReservationRecommendationDetailsOperations, + ReservationRecommendationsOperations, + ReservationTransactionsOperations, + ReservationsDetailsOperations, + ReservationsSummariesOperations, + TagsOperations, + UsageDetailsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class ConsumptionManagementClient: # pylint: disable=too-many-instance-attributes + +class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Consumption management client provides access to consumption resources for Azure Enterprise Subscriptions. @@ -65,9 +83,9 @@ class ConsumptionManagementClient: # pylint: disable=too-many-instance-attrib :vartype lots: azure.mgmt.consumption.aio.operations.LotsOperations :ivar credits: CreditsOperations operations :vartype credits: azure.mgmt.consumption.aio.operations.CreditsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: Azure Subscription ID. + :param subscription_id: Azure Subscription ID. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -83,31 +101,21 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = ConsumptionManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = ConsumptionManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.usage_details = UsageDetailsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.marketplaces = MarketplacesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.budgets = BudgetsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.tags = TagsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.charges = ChargesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.balances = BalancesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.usage_details = UsageDetailsOperations(self._client, self._config, self._serialize, self._deserialize) + self.marketplaces = MarketplacesOperations(self._client, self._config, self._serialize, self._deserialize) + self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.tags = TagsOperations(self._client, self._config, self._serialize, self._deserialize) + self.charges = ChargesOperations(self._client, self._config, self._serialize, self._deserialize) + self.balances = BalancesOperations(self._client, self._config, self._serialize, self._deserialize) self.reservations_summaries = ReservationsSummariesOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -123,31 +131,14 @@ def __init__( self.reservation_transactions = ReservationTransactionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.price_sheet = PriceSheetOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize - ) - self.aggregated_cost = AggregatedCostOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.events = EventsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.lots = LotsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.credits = CreditsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.aggregated_cost = AggregatedCostOperations(self._client, self._config, self._serialize, self._deserialize) + self.events = EventsOperations(self._client, self._config, self._serialize, self._deserialize) + self.lots = LotsOperations(self._client, self._config, self._serialize, self._deserialize) + self.credits = CreditsOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -156,7 +147,7 @@ def _send_request( >>> response = await client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py index bd4e5bf2cdbd8..33de5eb645bc9 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/__init__.py @@ -25,26 +25,27 @@ from ._credits_operations import CreditsOperations from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'UsageDetailsOperations', - 'MarketplacesOperations', - 'BudgetsOperations', - 'TagsOperations', - 'ChargesOperations', - 'BalancesOperations', - 'ReservationsSummariesOperations', - 'ReservationsDetailsOperations', - 'ReservationRecommendationsOperations', - 'ReservationRecommendationDetailsOperations', - 'ReservationTransactionsOperations', - 'PriceSheetOperations', - 'Operations', - 'AggregatedCostOperations', - 'EventsOperations', - 'LotsOperations', - 'CreditsOperations', + "UsageDetailsOperations", + "MarketplacesOperations", + "BudgetsOperations", + "TagsOperations", + "ChargesOperations", + "BalancesOperations", + "ReservationsSummariesOperations", + "ReservationsDetailsOperations", + "ReservationRecommendationsOperations", + "ReservationRecommendationDetailsOperations", + "ReservationTransactionsOperations", + "PriceSheetOperations", + "Operations", + "AggregatedCostOperations", + "EventsOperations", + "LotsOperations", + "CreditsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py index 0330ebe45e13a..719fcf0fd3ef8 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -18,10 +26,19 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._aggregated_cost_operations import build_get_by_management_group_request, build_get_for_billing_period_by_management_group_request -T = TypeVar('T') +from ...operations._aggregated_cost_operations import ( + build_get_by_management_group_request, + build_get_for_billing_period_by_management_group_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class AggregatedCostOperations: """ .. warning:: @@ -41,18 +58,14 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get_by_management_group( - self, - management_group_id: str, - filter: Optional[str] = None, - **kwargs: Any + self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any ) -> _models.ManagementGroupAggregatedCostResult: """Provides the aggregate cost of a management group and all child management groups by current billing period. - :param management_group_id: Azure Management Group ID. + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str :param filter: May be used to filter aggregated cost by properties/usageStart (Utc time), properties/usageEnd (Utc time). The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It @@ -60,38 +73,41 @@ async def get_by_management_group( key and value is separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ManagementGroupAggregatedCostResult, or the result of cls(response) + :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ManagementGroupAggregatedCostResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_by_management_group_request( management_group_id=management_group_id, - api_version=api_version, filter=filter, - template_url=self.get_by_management_group.metadata['url'], + api_version=api_version, + template_url=self.get_by_management_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -99,63 +115,64 @@ async def get_by_management_group( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ManagementGroupAggregatedCostResult', pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_management_group.metadata = {'url': "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost"} # type: ignore - + get_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost" + } @distributed_trace_async async def get_for_billing_period_by_management_group( - self, - management_group_id: str, - billing_period_name: str, - **kwargs: Any + self, management_group_id: str, billing_period_name: str, **kwargs: Any ) -> _models.ManagementGroupAggregatedCostResult: """Provides the aggregate cost of a management group and all child management groups by specified billing period. - :param management_group_id: Azure Management Group ID. + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str - :param billing_period_name: Billing Period Name. + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ManagementGroupAggregatedCostResult, or the result of cls(response) + :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ManagementGroupAggregatedCostResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_management_group_request( management_group_id=management_group_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_management_group.metadata['url'], + template_url=self.get_for_billing_period_by_management_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -163,12 +180,13 @@ async def get_for_billing_period_by_management_group( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ManagementGroupAggregatedCostResult', pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_for_billing_period_by_management_group.metadata = {'url': "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost"} # type: ignore - + get_for_billing_period_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py index 6b80c528c1bbf..bec3e86e7d3d4 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -18,10 +26,19 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._balances_operations import build_get_by_billing_account_request, build_get_for_billing_period_by_billing_account_request -T = TypeVar('T') +from ...operations._balances_operations import ( + build_get_by_billing_account_request, + build_get_for_billing_period_by_billing_account_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class BalancesOperations: """ .. warning:: @@ -41,50 +58,48 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async - async def get_by_billing_account( - self, - billing_account_id: str, - **kwargs: Any - ) -> _models.Balance: + async def get_by_billing_account(self, billing_account_id: str, **kwargs: Any) -> _models.Balance: """Gets the balances for a scope by billingAccountId. Balances are available via this API only for May 1, 2014 or later. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Balance, or the result of cls(response) + :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Balance] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_by_billing_account_request( billing_account_id=billing_account_id, api_version=api_version, - template_url=self.get_by_billing_account.metadata['url'], + template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -92,63 +107,64 @@ async def get_by_billing_account( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Balance', pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances"} # type: ignore - + get_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances" + } @distributed_trace_async async def get_for_billing_period_by_billing_account( - self, - billing_account_id: str, - billing_period_name: str, - **kwargs: Any + self, billing_account_id: str, billing_period_name: str, **kwargs: Any ) -> _models.Balance: """Gets the balances for a scope by billing period and billingAccountId. Balances are available via this API only for May 1, 2014 or later. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_period_name: Billing Period Name. + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Balance, or the result of cls(response) + :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Balance] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_billing_account_request( billing_account_id=billing_account_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_billing_account.metadata['url'], + template_url=self.get_for_billing_period_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -156,12 +172,13 @@ async def get_for_billing_period_by_billing_account( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Balance', pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_for_billing_period_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances"} # type: ignore - + get_for_billing_period_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py index 84cbce979809d..eefdd10b3308e 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,10 +29,21 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._budgets_operations import build_create_or_update_request, build_delete_request, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._budgets_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class BudgetsOperations: """ .. warning:: @@ -43,13 +63,8 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - scope: str, - **kwargs: Any - ) -> AsyncIterable[_models.BudgetsListResult]: + def list(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.Budget"]: """Lists all budgets for the defined scope. :param scope: The scope associated with budget operations. This includes @@ -65,48 +80,57 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection 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 BudgetsListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.BudgetsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Budget or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Budget] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.BudgetsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.BudgetsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( scope=scope, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - scope=scope, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -114,16 +138,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("BudgetsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -134,19 +156,12 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets"} # type: ignore + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets"} @distributed_trace_async - async def get( - self, - scope: str, - budget_name: str, - **kwargs: Any - ) -> _models.Budget: + async def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: """Gets the budget for the scope by budget name. :param scope: The scope associated with budget operations. This includes @@ -162,43 +177,46 @@ async def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection scope. Required. :type scope: str - :param budget_name: Budget Name. + :param budget_name: Budget Name. Required. :type budget_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Budget, or the result of cls(response) + :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Budget] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) - request = build_get_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -206,22 +224,23 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Budget', pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} - - @distributed_trace_async + @overload async def create_or_update( self, scope: str, budget_name: str, parameters: _models.Budget, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.Budget: """The operation to create or update a budget. You can optionally provide an eTag if desired as a @@ -241,30 +260,117 @@ async def create_or_update( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection scope. Required. :type scope: str - :param budget_name: Budget Name. + :param budget_name: Budget Name. Required. :type budget_name: str - :param parameters: Parameters supplied to the Create Budget operation. + :param parameters: Parameters supplied to the Create Budget operation. Required. :type parameters: ~azure.mgmt.consumption.models.Budget + :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: Budget, or the result of cls(response) + :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, scope: str, budget_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Budget: + """The operation to create or update a budget. You can optionally provide an eTag if desired as a + form of concurrency control. To obtain the latest eTag for a given budget, perform a get + operation prior to your put operation. + + :param scope: The scope associated with budget 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.Management/managementGroups/{managementGroupId}' for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :param parameters: Parameters supplied to the Create Budget 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: Budget or the result of cls(response) + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO], **kwargs: Any + ) -> _models.Budget: + """The operation to create or update a budget. You can optionally provide an eTag if desired as a + form of concurrency control. To obtain the latest eTag for a given budget, perform a get + operation prior to your put operation. + + :param scope: The scope associated with budget 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.Management/managementGroups/{managementGroupId}' for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :param parameters: Parameters supplied to the Create Budget operation. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.consumption.models.Budget 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: Budget or the result of cls(response) + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Budget] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) - _json = self._serialize.body(parameters, 'Budget') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Budget") request = build_create_or_update_request( scope=scope, @@ -272,18 +378,18 @@ async def create_or_update( api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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 + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -292,25 +398,21 @@ async def create_or_update( raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Budget', pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Budget', pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} # type: ignore + return deserialized # type: ignore + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} @distributed_trace_async async def delete( # pylint: disable=inconsistent-return-statements - self, - scope: str, - budget_name: str, - **kwargs: Any + self, scope: str, budget_name: str, **kwargs: Any ) -> None: """The operation to delete a budget. @@ -327,43 +429,46 @@ async def delete( # pylint: disable=inconsistent-return-statements '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection scope. Required. :type scope: str - :param budget_name: Budget Name. + :param budget_name: Budget Name. Required. :type budget_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: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.delete.metadata['url'], + template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -374,5 +479,4 @@ async def delete( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} # type: ignore - + delete.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py index ea57c0ce86b3f..a5e80610b7c45 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._charges_operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ChargesOperations: """ .. warning:: @@ -41,7 +55,6 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def list( self, @@ -69,7 +82,7 @@ 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 start_date: Start date. Default value is None. :type start_date: str @@ -86,41 +99,44 @@ async def list( None. :type apply: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChargesListResult, or the result of cls(response) + :return: ChargesListResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ChargesListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ChargesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ChargesListResult] = kwargs.pop("cls", None) - request = build_list_request( scope=scope, - api_version=api_version, start_date=start_date, end_date=end_date, filter=filter, apply=apply, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -128,12 +144,11 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ChargesListResult', pipeline_response) + deserialized = self._deserialize("ChargesListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/charges"} # type: ignore - + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/charges"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py index f75c370d2e8a5..e35c87cd34804 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._credits_operations import build_get_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class CreditsOperations: """ .. warning:: @@ -41,53 +55,52 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - billing_account_id: str, - billing_profile_id: str, - **kwargs: Any + self, billing_account_id: str, billing_profile_id: str, **kwargs: Any ) -> Optional[_models.CreditSummary]: """The credit summary by billingAccountId and billingProfileId. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CreditSummary, or the result of cls(response) + :return: CreditSummary or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.CreditSummary or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.CreditSummary]] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[Optional[_models.CreditSummary]] = kwargs.pop("cls", None) - request = build_get_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -97,12 +110,13 @@ async def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('CreditSummary', pipeline_response) + deserialized = self._deserialize("CreditSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary"} # type: ignore - + get.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py index 2e7e4d39b204c..91bc7ae68e49d 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,10 +28,19 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._events_operations import build_list_by_billing_account_request, build_list_by_billing_profile_request -T = TypeVar('T') +from ...operations._events_operations import ( + build_list_by_billing_account_request, + build_list_by_billing_profile_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class EventsOperations: """ .. warning:: @@ -42,72 +60,73 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_billing_profile( - self, - billing_account_id: str, - billing_profile_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> AsyncIterable[_models.Events]: + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> AsyncIterable["_models.EventSummary"]: """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile 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 - :return: An iterator like instance of either Events or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Events] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EventSummary or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.EventSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Events] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Events] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, - api_version=api_version, start_date=start_date, end_date=end_date, - template_url=self.list_by_billing_profile.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_profile_request( - billing_account_id=billing_account_id, - billing_profile_id=billing_profile_id, - api_version=api_version, - start_date=start_date, - end_date=end_date, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -115,16 +134,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -135,23 +152,20 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events"} # type: ignore + list_by_billing_profile.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events" + } @distributed_trace def list_by_billing_account( - self, - billing_account_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable[_models.Events]: + self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.EventSummary"]: """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the events by lotId, lotSource etc. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. @@ -159,46 +173,55 @@ def list_by_billing_account( value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Events or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Events] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EventSummary or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.EventSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Events] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Events] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_account_request( billing_account_id=billing_account_id, - api_version=api_version, filter=filter, - template_url=self.list_by_billing_account.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_account_request( - billing_account_id=billing_account_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -206,16 +229,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -226,8 +247,8 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events"} # type: ignore + list_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py index 2aa39a2edb048..300c7aafcca82 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,10 +28,20 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._lots_operations import build_list_by_billing_account_request, build_list_by_billing_profile_request, build_list_by_customer_request -T = TypeVar('T') +from ...operations._lots_operations import ( + build_list_by_billing_account_request, + build_list_by_billing_profile_request, + build_list_by_customer_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LotsOperations: """ .. warning:: @@ -42,62 +61,67 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_billing_profile( - self, - billing_account_id: str, - billing_profile_id: str, - **kwargs: Any - ) -> AsyncIterable[_models.Lots]: + self, billing_account_id: str, billing_profile_id: str, **kwargs: Any + ) -> AsyncIterable["_models.LotSummary"]: """Lists all Azure credits for a billing account or a billing profile. The API is only supported for Microsoft Customer Agreements (MCA) billing accounts. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Lots or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Lots] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LotSummary or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Lots] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Lots] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.list_by_billing_profile.metadata['url'], + template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_profile_request( - billing_account_id=billing_account_id, - billing_profile_id=billing_profile_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -105,16 +129,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -125,24 +147,21 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots"} # type: ignore + list_by_billing_profile.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots" + } @distributed_trace def list_by_billing_account( - self, - billing_account_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable[_models.Lots]: + self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.LotSummary"]: """Lists all Microsoft Azure consumption commitments for a billing account. The API is only supported for Microsoft Customer Agreements (MCA) and Direct Enterprise Agreement (EA) billing accounts. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the lots by Status, Source etc. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag @@ -150,46 +169,55 @@ def list_by_billing_account( value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Lots or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Lots] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LotSummary or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Lots] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Lots] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_account_request( billing_account_id=billing_account_id, - api_version=api_version, filter=filter, - template_url=self.list_by_billing_account.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_account_request( - billing_account_id=billing_account_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -197,16 +225,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -217,74 +243,78 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots"} # type: ignore + list_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots" + } @distributed_trace def list_by_customer( - self, - billing_account_id: str, - customer_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable[_models.Lots]: + self, billing_account_id: str, customer_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.LotSummary"]: """Lists all Azure credits for a customer. The API is only supported for Microsoft Partner Agreements (MPA) billing accounts. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param customer_id: Customer ID. + :param customer_id: Customer ID. Required. :type customer_id: str :param filter: May be used to filter the lots by Status, Source etc. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Lots or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Lots] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LotSummary or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Lots] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Lots] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_customer_request( billing_account_id=billing_account_id, customer_id=customer_id, - api_version=api_version, filter=filter, - template_url=self.list_by_customer.metadata['url'], + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_customer_request( - billing_account_id=billing_account_id, - customer_id=customer_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -292,16 +322,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -312,8 +340,8 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots"} # type: ignore + list_by_customer.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py index 1e775b180fb31..924441566518f 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +29,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._marketplaces_operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class MarketplacesOperations: """ .. warning:: @@ -42,7 +57,6 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( self, @@ -51,7 +65,7 @@ def list( top: Optional[int] = None, skiptoken: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable[_models.MarketplacesListResult]: + ) -> AsyncIterable["_models.Marketplace"]: """Lists the marketplaces for a scope at the defined scope. Marketplaces are available via this API only for May 1, 2014 or later. @@ -66,6 +80,7 @@ def list( '/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. For e.g. to specify billing period at department scope use '/providers/Microsoft.Billing/departments/{departmentId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. + Required. :type scope: str :param filter: May be used to filter marketplaces by properties/usageEnd (Utc time), properties/usageStart (Utc time), properties/resourceGroup, properties/instanceName or @@ -81,52 +96,57 @@ def list( value is None. :type skiptoken: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either MarketplacesListResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.MarketplacesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Marketplace or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Marketplace] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.MarketplacesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.MarketplacesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( scope=scope, - api_version=api_version, filter=filter, top=top, skiptoken=skiptoken, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - scope=scope, - api_version=api_version, - filter=filter, - top=top, - skiptoken=skiptoken, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -134,28 +154,24 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("MarketplacesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + 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, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/marketplaces"} # type: ignore + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/marketplaces"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py index 8f7e8e888e23e..715254cec8704 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +29,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class Operations: """ .. warning:: @@ -42,52 +57,58 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable[_models.OperationListResult]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available consumption 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.consumption.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.consumption.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.OperationListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -95,16 +116,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -115,8 +134,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.Consumption/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Consumption/operations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_patch.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_patch.py index 0ad201a8c586e..f7dd32510333d 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_patch.py @@ -10,6 +10,7 @@ __all__: List[str] = [] # Add all objects you want publicly available to users at this package level + def patch_sdk(): """Do not remove from this file. diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py index 4f02f345f2aa6..4bb0b620ad7fe 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._price_sheet_operations import build_get_by_billing_period_request, build_get_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class PriceSheetOperations: """ .. warning:: @@ -41,14 +55,9 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - expand: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any + self, expand: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> _models.PriceSheetResult: """Gets the price sheet for a subscription. Price sheet is available via this API only for May 1, 2014 or later. @@ -65,40 +74,43 @@ async def get( None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: PriceSheetResult, or the result of cls(response) + :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PriceSheetResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_request( subscription_id=self._config.subscription_id, - api_version=api_version, expand=expand, skiptoken=skiptoken, top=top, - template_url=self.get.metadata['url'], + api_version=api_version, + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -106,15 +118,14 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PriceSheetResult', pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} @distributed_trace_async async def get_by_billing_period( @@ -128,7 +139,7 @@ async def get_by_billing_period( """Get the price sheet for a scope by subscriptionId and billing period. Price sheet is available via this API only for May 1, 2014 or later. - :param billing_period_name: Billing Period Name. + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :param expand: May be used to expand the properties/meterDetails within a price sheet. By default, these fields are not included when returning price sheet. Default value is None. @@ -142,41 +153,44 @@ async def get_by_billing_period( None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: PriceSheetResult, or the result of cls(response) + :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PriceSheetResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_by_billing_period_request( - subscription_id=self._config.subscription_id, billing_period_name=billing_period_name, - api_version=api_version, + subscription_id=self._config.subscription_id, expand=expand, skiptoken=skiptoken, top=top, - template_url=self.get_by_billing_period.metadata['url'], + api_version=api_version, + template_url=self.get_by_billing_period.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -184,12 +198,13 @@ async def get_by_billing_period( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PriceSheetResult', pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_period.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default"} # type: ignore - + get_by_billing_period.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py index 7bc5af234fe27..dd832048dc3e5 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar, 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.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._reservation_recommendation_details_operations import build_get_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReservationRecommendationDetailsOperations: """ .. warning:: @@ -41,15 +55,14 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( self, resource_scope: str, - scope: Union[str, "_models.Scope"], + scope: Union[str, _models.Scope], region: str, - term: Union[str, "_models.Term"], - look_back_period: Union[str, "_models.LookBackPeriod"], + term: Union[str, _models.Term], + look_back_period: Union[str, _models.LookBackPeriod], product: str, **kwargs: Any ) -> Optional[_models.ReservationRecommendationDetailsModel]: @@ -60,57 +73,62 @@ async def get( '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope. + for billingProfile scope. Required. :type resource_scope: str - :param scope: Scope of the reservation. + :param scope: Scope of the reservation. Known values are: "Single" and "Shared". Required. :type scope: str or ~azure.mgmt.consumption.models.Scope - :param region: Used to select the region the recommendation should be generated for. + :param region: Used to select the region the recommendation should be generated for. Required. :type region: str - :param term: Specify length of reservation recommendation term. + :param term: Specify length of reservation recommendation term. Known values are: "P1Y" and + "P3Y". Required. :type term: str or ~azure.mgmt.consumption.models.Term :param look_back_period: Filter the time period on which reservation recommendation results are - based. + based. Known values are: "Last7Days", "Last30Days", and "Last60Days". Required. :type look_back_period: str or ~azure.mgmt.consumption.models.LookBackPeriod :param product: Filter the products for which reservation recommendation results are generated. Examples: Standard_DS1_v2 (for VM), Premium_SSD_Managed_Disks_P30 (for Managed Disks). + Required. :type product: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationRecommendationDetailsModel, or the result of cls(response) + :return: ReservationRecommendationDetailsModel or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] = kwargs.pop("cls", None) - request = build_get_request( resource_scope=resource_scope, - api_version=api_version, scope=scope, region=region, term=term, look_back_period=look_back_period, product=product, - template_url=self.get.metadata['url'], + api_version=api_version, + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -120,12 +138,11 @@ async def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ReservationRecommendationDetailsModel', pipeline_response) + deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails"} # type: ignore - + get.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py index 33ceebe3fdeb6..b23a984c7447f 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +29,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._reservation_recommendations_operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReservationRecommendationsOperations: """ .. warning:: @@ -42,14 +57,10 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( - self, - resource_scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable[_models.ReservationRecommendationsListResult]: + self, resource_scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ReservationRecommendation"]: """List of recommendations for purchasing reserved instances. :param resource_scope: The scope associated with reservation recommendations operations. This @@ -57,7 +68,7 @@ def list( '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope. + for billingProfile scope. Required. :type resource_scope: str :param filter: May be used to filter reservationRecommendations by: properties/scope with allowed values ['Single', 'Shared'] and default value 'Single'; properties/resourceType with @@ -68,48 +79,57 @@ def list( default value 'Last7Days'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationRecommendationsListResult or the result - of cls(response) + :return: An iterator like instance of either ReservationRecommendation or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationRecommendationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationRecommendation] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationRecommendationsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationRecommendationsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( resource_scope=resource_scope, - api_version=api_version, filter=filter, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - resource_scope=resource_scope, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -117,16 +137,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationRecommendationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -137,8 +155,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations"} # type: ignore + list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py index c76ab098cb365..15671e3cf4a93 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +29,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._reservation_transactions_operations import build_list_by_billing_profile_request, build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReservationTransactionsOperations: """ .. warning:: @@ -42,64 +57,77 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( - self, - billing_account_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable[_models.ReservationTransactionsListResult]: - """List of transactions for reserved instances on billing account scope. - - :param billing_account_id: BillingAccount ID. + self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ReservationTransaction"]: + """List of transactions for reserved instances on billing account scope. Note: The refund + transactions are posted along with its purchase transaction (i.e. in the purchase billing + month). For example, The refund is requested in May 2021. This refund transaction will have + event date as May 2021 but the billing month as April 2020 when the reservation purchase was + made. + + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: Filter reservation transactions by date range. The properties/EventDate for - start date and end date. The filter supports 'le' and 'ge'. Default value is None. + start date and end date. The filter supports 'le' and 'ge'. Note: API returns data for the + entire start date's and end date's billing month. For example, filter + properties/eventDate+ge+2020-01-01+AND+properties/eventDate+le+2020-12-29 will include data for + the entire December 2020 month (i.e. will contain records for dates December 30 and 31). + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationTransactionsListResult or the result of + :return: An iterator like instance of either ReservationTransaction or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationTransactionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationTransactionsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationTransactionsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( billing_account_id=billing_account_id, - api_version=api_version, filter=filter, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - billing_account_id=billing_account_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -107,16 +135,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationTransactionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -127,74 +153,85 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions"} # type: ignore + list.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions" + } @distributed_trace def list_by_billing_profile( - self, - billing_account_id: str, - billing_profile_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable[_models.ModernReservationTransactionsListResult]: - """List of transactions for reserved instances on billing account scope. - - :param billing_account_id: BillingAccount ID. + self, billing_account_id: str, billing_profile_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ModernReservationTransaction"]: + """List of transactions for reserved instances on billing profile scope. The refund transactions + are posted along with its purchase transaction (i.e. in the purchase billing month). For + example, The refund is requested in May 2021. This refund transaction will have event date as + May 2021 but the billing month as April 2020 when the reservation purchase was made. + + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str :param filter: Filter reservation transactions by date range. The properties/EventDate for - start date and end date. The filter supports 'le' and 'ge'. Default value is None. + start date and end date. The filter supports 'le' and 'ge'. Note: API returns data for the + entire start date's and end date's billing month. For example, filter + properties/eventDate+ge+2020-01-01+AND+properties/eventDate+le+2020-12-29 will include data for + entire December 2020 month (i.e. will contain records for dates December 30 and 31). Default + value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ModernReservationTransactionsListResult or the - result of cls(response) + :return: An iterator like instance of either ModernReservationTransaction or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ModernReservationTransactionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ModernReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ModernReservationTransactionsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ModernReservationTransactionsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, - api_version=api_version, filter=filter, - template_url=self.list_by_billing_profile.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_profile_request( - billing_account_id=billing_account_id, - billing_profile_id=billing_profile_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -202,16 +239,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ModernReservationTransactionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -222,8 +257,8 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions"} # type: ignore + list_by_billing_profile.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py index 1d88130fe2909..cb74a06054b84 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,10 +28,20 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._reservations_details_operations import build_list_by_reservation_order_and_reservation_request, build_list_by_reservation_order_request, build_list_request -T = TypeVar('T') +from ...operations._reservations_details_operations import ( + build_list_by_reservation_order_and_reservation_request, + build_list_by_reservation_order_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReservationsDetailsOperations: """ .. warning:: @@ -42,64 +61,70 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_reservation_order( - self, - reservation_order_id: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable[_models.ReservationDetailsListResult]: - """Lists the reservations details for provided date range. + self, reservation_order_id: str, filter: str, **kwargs: Any + ) -> AsyncIterable["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, + API call should be made with smaller date ranges. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param filter: Filter reservation details by date range. The properties/UsageDate for start - date and end date. The filter supports 'le' and 'ge'. + date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationDetailsListResult or the result of - cls(response) + :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, - api_version=api_version, filter=filter, - template_url=self.list_by_reservation_order.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -107,16 +132,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -127,74 +150,79 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_reservation_order.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails"} # type: ignore + list_by_reservation_order.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails" + } @distributed_trace def list_by_reservation_order_and_reservation( - self, - reservation_order_id: str, - reservation_id: str, - filter: str, - **kwargs: Any - ) -> AsyncIterable[_models.ReservationDetailsListResult]: - """Lists the reservations details for provided date range. + self, reservation_order_id: str, reservation_id: str, filter: str, **kwargs: Any + ) -> AsyncIterable["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, + API call should be made with smaller date ranges. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the reservation. + :param reservation_id: Id of the reservation. Required. :type reservation_id: str :param filter: Filter reservation details by date range. The properties/UsageDate for start - date and end date. The filter supports 'le' and 'ge'. + date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationDetailsListResult or the result of - cls(response) + :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, - api_version=api_version, filter=filter, - template_url=self.list_by_reservation_order_and_reservation.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_and_reservation_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -202,16 +230,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -222,11 +248,11 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_reservation_order_and_reservation.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails"} # type: ignore + list_by_reservation_order_and_reservation.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails" + } @distributed_trace def list( @@ -238,14 +264,16 @@ def list( reservation_id: Optional[str] = None, reservation_order_id: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable[_models.ReservationDetailsListResult]: - """Lists the reservations details for the defined scope and provided date range. + ) -> AsyncIterable["_models.ReservationDetail"]: + """Lists the reservations details for the defined scope and provided date range. Note: ARM has a + payload size limit of 12MB, so currently callers get 502 when the response size exceeds the ARM + limit. In such cases, API call should be made with smaller date ranges. :param resource_scope: The scope associated with reservations details operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope (legacy), and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for BillingProfile scope (modern). + for BillingProfile scope (modern). Required. :type resource_scope: str :param start_date: Start date. Only applicable when querying with billing profile. Default value is None. @@ -264,56 +292,60 @@ def list( Filter to a specific reservation order. Default value is None. :type reservation_order_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationDetailsListResult or the result of - cls(response) + :return: An iterator like instance of either ReservationDetail or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( resource_scope=resource_scope, - api_version=api_version, start_date=start_date, end_date=end_date, filter=filter, reservation_id=reservation_id, reservation_order_id=reservation_order_id, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - resource_scope=resource_scope, - api_version=api_version, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -321,16 +353,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -341,8 +371,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails"} # type: ignore + list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py index 0d2a71186f552..2c5bb97e1b109 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,10 +28,20 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._reservations_summaries_operations import build_list_by_reservation_order_and_reservation_request, build_list_by_reservation_order_request, build_list_request -T = TypeVar('T') +from ...operations._reservations_summaries_operations import ( + build_list_by_reservation_order_and_reservation_request, + build_list_by_reservation_order_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReservationsSummariesOperations: """ .. warning:: @@ -42,69 +61,75 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_reservation_order( self, reservation_order_id: str, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable[_models.ReservationSummariesListResult]: + ) -> AsyncIterable["_models.ReservationSummary"]: """Lists the reservations summaries for daily or monthly grain. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param grain: Can be daily or monthly. + :param grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. :type grain: str or ~azure.mgmt.consumption.models.Datagrain :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationSummariesListResult or the result of - cls(response) + :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummariesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationSummariesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, - api_version=api_version, grain=grain, filter=filter, - template_url=self.list_by_reservation_order.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - grain=grain, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -112,16 +137,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -132,79 +155,85 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_reservation_order.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries"} # type: ignore + list_by_reservation_order.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries" + } @distributed_trace def list_by_reservation_order_and_reservation( self, reservation_order_id: str, reservation_id: str, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable[_models.ReservationSummariesListResult]: + ) -> AsyncIterable["_models.ReservationSummary"]: """Lists the reservations summaries for daily or monthly grain. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the reservation. + :param reservation_id: Id of the reservation. Required. :type reservation_id: str - :param grain: Can be daily or monthly. + :param grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. :type grain: str or ~azure.mgmt.consumption.models.Datagrain :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationSummariesListResult or the result of - cls(response) + :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummariesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationSummariesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, - api_version=api_version, grain=grain, filter=filter, - template_url=self.list_by_reservation_order_and_reservation.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_and_reservation_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - grain=grain, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -212,16 +241,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -232,33 +259,33 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_reservation_order_and_reservation.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries"} # type: ignore + list_by_reservation_order_and_reservation.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries" + } @distributed_trace def list( self, resource_scope: str, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], start_date: Optional[str] = None, end_date: Optional[str] = None, filter: Optional[str] = None, reservation_id: Optional[str] = None, reservation_order_id: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable[_models.ReservationSummariesListResult]: + ) -> AsyncIterable["_models.ReservationSummary"]: """Lists the reservations summaries for the defined scope daily or monthly grain. :param resource_scope: The scope associated with reservations summaries operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope (legacy), and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for BillingProfile scope (modern). + for BillingProfile scope (modern). Required. :type resource_scope: str - :param grain: Can be daily or monthly. + :param grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. :type grain: str or ~azure.mgmt.consumption.models.Datagrain :param start_date: Start date. Only applicable when querying with billing profile. Default value is None. @@ -277,58 +304,61 @@ def list( Filter to a specific reservation order. Default value is None. :type reservation_order_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationSummariesListResult or the result of - cls(response) + :return: An iterator like instance of either ReservationSummary or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummariesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationSummariesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( resource_scope=resource_scope, - api_version=api_version, grain=grain, start_date=start_date, end_date=end_date, filter=filter, reservation_id=reservation_id, reservation_order_id=reservation_order_id, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - resource_scope=resource_scope, - api_version=api_version, - grain=grain, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -336,16 +366,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -356,8 +384,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries"} # type: ignore + list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py index 6840e46221c3f..ec7c05804fe90 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py @@ -6,9 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +27,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._tags_operations import build_get_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class TagsOperations: """ .. warning:: @@ -41,13 +55,8 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async - async def get( - self, - scope: str, - **kwargs: Any - ) -> Optional[_models.TagsResult]: + async def get(self, scope: str, **kwargs: Any) -> Optional[_models.TagsResult]: """Get all available tag keys for the defined scope. :param scope: The scope associated with tags operations. This includes @@ -59,40 +68,43 @@ async def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount scope and '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group - scope.. + scope.. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: TagsResult, or the result of cls(response) + :return: TagsResult or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.TagsResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.TagsResult]] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[Optional[_models.TagsResult]] = kwargs.pop("cls", None) - request = build_get_request( scope=scope, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -102,12 +114,11 @@ async def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('TagsResult', pipeline_response) + deserialized = self._deserialize("TagsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/tags"} # type: ignore - + get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/tags"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py index 2be5e7c19f207..9b7ee901cf4ce 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py @@ -6,10 +6,19 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +29,15 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._usage_details_operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class UsageDetailsOperations: """ .. warning:: @@ -42,7 +57,6 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( self, @@ -51,9 +65,9 @@ def list( filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, - metric: Optional[Union[str, "_models.Metrictype"]] = None, + metric: Optional[Union[str, _models.Metrictype]] = None, **kwargs: Any - ) -> AsyncIterable[_models.UsageDetailsListResult]: + ) -> AsyncIterable["_models.UsageDetail"]: """Lists the usage details for the defined scope. Usage details are available via this API only for May 1, 2014 or later. @@ -75,7 +89,7 @@ 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/additionalInfo or properties/meterDetails within a list of usage details. By default, these fields are not included when listing usage @@ -97,59 +111,63 @@ def list( :param top: May be used to limit the number of results to the most recent N usageDetails. Default value is None. :type top: int - :param metric: Allows to select different type of cost/usage records. Default value is None. + :param metric: Allows to select different type of cost/usage records. Known values are: + "actualcost", "amortizedcost", and "usage". Default value is None. :type metric: str or ~azure.mgmt.consumption.models.Metrictype :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either UsageDetailsListResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.UsageDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either UsageDetail or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.UsageDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.UsageDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.UsageDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( scope=scope, - api_version=api_version, expand=expand, filter=filter, skiptoken=skiptoken, top=top, metric=metric, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - scope=scope, - api_version=api_version, - expand=expand, - filter=filter, - skiptoken=skiptoken, - top=top, - metric=metric, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -157,16 +175,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("UsageDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -177,8 +193,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/usageDetails"} # type: ignore + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/usageDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py index cd1a0082d80ec..134b6775b0699 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/__init__.py @@ -46,8 +46,11 @@ from ._models_py3 import MeterDetailsResponse from ._models_py3 import ModernChargeSummary from ._models_py3 import ModernReservationRecommendation +from ._models_py3 import ModernReservationRecommendationProperties from ._models_py3 import ModernReservationTransaction from ._models_py3 import ModernReservationTransactionsListResult +from ._models_py3 import ModernSharedScopeReservationRecommendationProperties +from ._models_py3 import ModernSingleScopeReservationRecommendationProperties from ._models_py3 import ModernUsageDetail from ._models_py3 import Notification from ._models_py3 import Operation @@ -79,123 +82,124 @@ from ._models_py3 import UsageDetail from ._models_py3 import UsageDetailsListResult - -from ._consumption_management_client_enums import ( - BillingFrequency, - BudgetOperatorType, - CategoryType, - ChargeSummaryKind, - CultureCode, - Datagrain, - EventType, - LookBackPeriod, - LotSource, - Metrictype, - OperatorType, - PricingModelType, - ReservationRecommendationKind, - Scope, - Status, - Term, - ThresholdType, - TimeGrainType, - UsageDetailsKind, -) +from ._consumption_management_client_enums import BillingFrequency +from ._consumption_management_client_enums import BudgetOperatorType +from ._consumption_management_client_enums import CategoryType +from ._consumption_management_client_enums import ChargeSummaryKind +from ._consumption_management_client_enums import CultureCode +from ._consumption_management_client_enums import Datagrain +from ._consumption_management_client_enums import EventType +from ._consumption_management_client_enums import LookBackPeriod +from ._consumption_management_client_enums import LotSource +from ._consumption_management_client_enums import Metrictype +from ._consumption_management_client_enums import OperatorType +from ._consumption_management_client_enums import PricingModelType +from ._consumption_management_client_enums import ReservationRecommendationKind +from ._consumption_management_client_enums import Scope +from ._consumption_management_client_enums import Status +from ._consumption_management_client_enums import Term +from ._consumption_management_client_enums import ThresholdType +from ._consumption_management_client_enums import TimeGrainType +from ._consumption_management_client_enums import UsageDetailsKind from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Amount', - 'AmountWithExchangeRate', - 'Balance', - 'BalancePropertiesAdjustmentDetailsItem', - 'BalancePropertiesNewPurchasesDetailsItem', - 'Budget', - 'BudgetComparisonExpression', - 'BudgetFilter', - 'BudgetFilterProperties', - 'BudgetTimePeriod', - 'BudgetsListResult', - 'ChargeSummary', - 'ChargesListResult', - 'CreditBalanceSummary', - 'CreditSummary', - 'CurrentSpend', - 'DownloadProperties', - 'ErrorDetails', - 'ErrorResponse', - 'EventSummary', - 'Events', - 'ForecastSpend', - 'HighCasedErrorDetails', - 'HighCasedErrorResponse', - 'LegacyChargeSummary', - 'LegacyReservationRecommendation', - 'LegacyReservationRecommendationProperties', - 'LegacyReservationTransaction', - 'LegacySharedScopeReservationRecommendationProperties', - 'LegacySingleScopeReservationRecommendationProperties', - 'LegacyUsageDetail', - 'LotSummary', - 'Lots', - 'ManagementGroupAggregatedCostResult', - 'Marketplace', - 'MarketplacesListResult', - 'MeterDetails', - 'MeterDetailsResponse', - 'ModernChargeSummary', - 'ModernReservationRecommendation', - 'ModernReservationTransaction', - 'ModernReservationTransactionsListResult', - 'ModernUsageDetail', - 'Notification', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'PriceSheetProperties', - 'PriceSheetResult', - 'ProxyResource', - 'Reseller', - 'ReservationDetail', - 'ReservationDetailsListResult', - 'ReservationRecommendation', - 'ReservationRecommendationDetailsCalculatedSavingsProperties', - 'ReservationRecommendationDetailsModel', - 'ReservationRecommendationDetailsResourceProperties', - 'ReservationRecommendationDetailsSavingsProperties', - 'ReservationRecommendationDetailsUsageProperties', - 'ReservationRecommendationsListResult', - 'ReservationSummariesListResult', - 'ReservationSummary', - 'ReservationTransaction', - 'ReservationTransactionResource', - 'ReservationTransactionsListResult', - 'Resource', - 'ResourceAttributes', - 'SkuProperty', - 'Tag', - 'TagsResult', - 'UsageDetail', - 'UsageDetailsListResult', - 'BillingFrequency', - 'BudgetOperatorType', - 'CategoryType', - 'ChargeSummaryKind', - 'CultureCode', - 'Datagrain', - 'EventType', - 'LookBackPeriod', - 'LotSource', - 'Metrictype', - 'OperatorType', - 'PricingModelType', - 'ReservationRecommendationKind', - 'Scope', - 'Status', - 'Term', - 'ThresholdType', - 'TimeGrainType', - 'UsageDetailsKind', + "Amount", + "AmountWithExchangeRate", + "Balance", + "BalancePropertiesAdjustmentDetailsItem", + "BalancePropertiesNewPurchasesDetailsItem", + "Budget", + "BudgetComparisonExpression", + "BudgetFilter", + "BudgetFilterProperties", + "BudgetTimePeriod", + "BudgetsListResult", + "ChargeSummary", + "ChargesListResult", + "CreditBalanceSummary", + "CreditSummary", + "CurrentSpend", + "DownloadProperties", + "ErrorDetails", + "ErrorResponse", + "EventSummary", + "Events", + "ForecastSpend", + "HighCasedErrorDetails", + "HighCasedErrorResponse", + "LegacyChargeSummary", + "LegacyReservationRecommendation", + "LegacyReservationRecommendationProperties", + "LegacyReservationTransaction", + "LegacySharedScopeReservationRecommendationProperties", + "LegacySingleScopeReservationRecommendationProperties", + "LegacyUsageDetail", + "LotSummary", + "Lots", + "ManagementGroupAggregatedCostResult", + "Marketplace", + "MarketplacesListResult", + "MeterDetails", + "MeterDetailsResponse", + "ModernChargeSummary", + "ModernReservationRecommendation", + "ModernReservationRecommendationProperties", + "ModernReservationTransaction", + "ModernReservationTransactionsListResult", + "ModernSharedScopeReservationRecommendationProperties", + "ModernSingleScopeReservationRecommendationProperties", + "ModernUsageDetail", + "Notification", + "Operation", + "OperationDisplay", + "OperationListResult", + "PriceSheetProperties", + "PriceSheetResult", + "ProxyResource", + "Reseller", + "ReservationDetail", + "ReservationDetailsListResult", + "ReservationRecommendation", + "ReservationRecommendationDetailsCalculatedSavingsProperties", + "ReservationRecommendationDetailsModel", + "ReservationRecommendationDetailsResourceProperties", + "ReservationRecommendationDetailsSavingsProperties", + "ReservationRecommendationDetailsUsageProperties", + "ReservationRecommendationsListResult", + "ReservationSummariesListResult", + "ReservationSummary", + "ReservationTransaction", + "ReservationTransactionResource", + "ReservationTransactionsListResult", + "Resource", + "ResourceAttributes", + "SkuProperty", + "Tag", + "TagsResult", + "UsageDetail", + "UsageDetailsListResult", + "BillingFrequency", + "BudgetOperatorType", + "CategoryType", + "ChargeSummaryKind", + "CultureCode", + "Datagrain", + "EventType", + "LookBackPeriod", + "LotSource", + "Metrictype", + "OperatorType", + "PricingModelType", + "ReservationRecommendationKind", + "Scope", + "Status", + "Term", + "ThresholdType", + "TimeGrainType", + "UsageDetailsKind", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py index b516bcfee68e8..ecb66e0217dd7 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py @@ -11,35 +11,34 @@ class BillingFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The billing frequency. - """ + """The billing frequency.""" MONTH = "Month" QUARTER = "Quarter" YEAR = "Year" + class BudgetOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The operator to use for comparison. - """ + """The operator to use for comparison.""" + + IN = "In" - IN_ENUM = "In" class CategoryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The category of the budget, whether the budget tracks cost or usage. - """ + """The category of the budget, whether the budget tracks cost or usage.""" COST = "Cost" + class ChargeSummaryKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the kind of charge summary. - """ + """Specifies the kind of charge summary.""" LEGACY = "legacy" MODERN = "modern" + class CultureCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Language in which the recipient will receive the notification - """ + """Language in which the recipient will receive the notification.""" EN_US = "en-us" JA_JP = "ja-jp" @@ -63,16 +62,18 @@ class CultureCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): PT_PT = "pt-pt" SV_SE = "sv-se" + class Datagrain(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Datagrain.""" - #: Daily grain of data. + #: Daily grain of data DAILY_GRAIN = "daily" - #: Monthly grain of data. + #: Monthly grain of data MONTHLY_GRAIN = "monthly" + class EventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Identifies the type of the event. - """ + """Identifies the type of the event.""" SETTLED_CHARGES = "SettledCharges" PENDING_CHARGES = "PendingCharges" @@ -83,24 +84,28 @@ class EventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): NEW_CREDIT = "NewCredit" CREDIT_EXPIRED = "CreditExpired" + class LookBackPeriod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """LookBackPeriod.""" - #: Use 7 days of data for recommendations. + #: Use 7 days of data for recommendations LAST07_DAYS = "Last7Days" - #: Use 30 days of data for recommendations. + #: Use 30 days of data for recommendations LAST30_DAYS = "Last30Days" - #: Use 60 days of data for recommendations. + #: Use 60 days of data for recommendations LAST60_DAYS = "Last60Days" + class LotSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The source of the lot. - """ + """The source of the lot.""" PURCHASED_CREDIT = "PurchasedCredit" PROMOTIONAL_CREDIT = "PromotionalCredit" CONSUMPTION_COMMITMENT = "ConsumptionCommitment" + class Metrictype(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Metrictype.""" #: Actual cost data. ACTUAL_COST_METRIC_TYPE = "actualcost" @@ -109,37 +114,46 @@ class Metrictype(str, Enum, metaclass=CaseInsensitiveEnumMeta): #: Usage data. USAGE_METRIC_TYPE = "usage" + class OperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The comparison operator. - """ + """The comparison operator.""" + #: Alert will be triggered if the evaluated cost is the same as threshold value. Note: It’s not + #: recommended to use this OperatorType as there’s low chance of cost being exactly the same as + #: threshold value, leading to missing of your alert. This OperatorType will be deprecated in + #: future. EQUAL_TO = "EqualTo" + #: Alert will be triggered if the evaluated cost is greater than the threshold value. Note: This + #: is the recommended OperatorType while configuring Budget Alert. GREATER_THAN = "GreaterThan" + #: Alert will be triggered if the evaluated cost is greater than or equal to the threshold value. GREATER_THAN_OR_EQUAL_TO = "GreaterThanOrEqualTo" + class PricingModelType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Identifier that indicates how the meter is priced. - """ + """Identifier that indicates how the meter is priced.""" ON_DEMAND = "On Demand" RESERVATION = "Reservation" SPOT = "Spot" + class ReservationRecommendationKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the kind of reservation recommendation. - """ + """Specifies the kind of reservation recommendation.""" LEGACY = "legacy" MODERN = "modern" + class Scope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Scope.""" SINGLE = "Single" SHARED = "Shared" + class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The status of the lot. - """ + """The status of the lot.""" NONE = "None" ACTIVE = "Active" @@ -148,23 +162,29 @@ class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): COMPLETE = "Complete" CANCELED = "Canceled" + class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Term.""" - #: 1 year reservation term. + #: 1 year reservation term P1_Y = "P1Y" - #: 3 year reservation term. + #: 3 year reservation term P3_Y = "P3Y" + class ThresholdType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of threshold - """ + """The type of threshold.""" + #: Actual costs budget alerts notify when the actual accrued cost exceeds the allocated budget . ACTUAL = "Actual" + #: Forecasted costs budget alerts provide advanced notification that your spending trends are + #: likely to exceed your allocated budget, as it relies on forecasted cost predictions. FORECASTED = "Forecasted" + class TimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The time covered by a budget. Tracking of the amount will be reset based on the time grain. - BillingMonth, BillingQuarter, and BillingAnnual are only supported by WD customers + BillingMonth, BillingQuarter, and BillingAnnual are only supported by WD customers. """ MONTHLY = "Monthly" @@ -174,9 +194,9 @@ class TimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): BILLING_QUARTER = "BillingQuarter" BILLING_ANNUAL = "BillingAnnual" + class UsageDetailsKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the kind of usage details. - """ + """Specifies the kind of usage details.""" LEGACY = "legacy" MODERN = "modern" diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py index 73c90fc3f5665..a3d280e095a92 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -9,15 +10,14 @@ import datetime from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - import __init__ as _models + from .. import models as _models -class Amount(msrest.serialization.Model): +class Amount(_serialization.Model): """The amount plus currency . Variables are only populated by the server, and will be ignored when sending a request. @@ -29,22 +29,18 @@ class Amount(msrest.serialization.Model): """ _validation = { - 'currency': {'readonly': True}, - 'value': {'readonly': True}, + "currency": {"readonly": True}, + "value": {"readonly": True}, } _attribute_map = { - 'currency': {'key': 'currency', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, + "currency": {"key": "currency", "type": "str"}, + "value": {"key": "value", "type": "float"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Amount, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.currency = None self.value = None @@ -65,31 +61,27 @@ class AmountWithExchangeRate(Amount): """ _validation = { - 'currency': {'readonly': True}, - 'value': {'readonly': True}, - 'exchange_rate': {'readonly': True}, - 'exchange_rate_month': {'readonly': True}, + "currency": {"readonly": True}, + "value": {"readonly": True}, + "exchange_rate": {"readonly": True}, + "exchange_rate_month": {"readonly": True}, } _attribute_map = { - 'currency': {'key': 'currency', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, - 'exchange_rate': {'key': 'exchangeRate', 'type': 'float'}, - 'exchange_rate_month': {'key': 'exchangeRateMonth', 'type': 'int'}, + "currency": {"key": "currency", "type": "str"}, + "value": {"key": "value", "type": "float"}, + "exchange_rate": {"key": "exchangeRate", "type": "float"}, + "exchange_rate_month": {"key": "exchangeRateMonth", "type": "int"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(AmountWithExchangeRate, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.exchange_rate = None self.exchange_rate_month = None -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -102,33 +94,29 @@ class Resource(msrest.serialization.Model): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -136,7 +124,7 @@ def __init__( self.tags = None -class Balance(Resource): +class Balance(Resource): # pylint: disable=too-many-instance-attributes """A balance resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -149,7 +137,7 @@ class Balance(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar currency: The ISO currency in which the meter is charged, for example, USD. :vartype currency: str @@ -174,7 +162,8 @@ class Balance(Resource): :vartype total_usage: float :ivar azure_marketplace_service_charges: Total charges for Azure Marketplace. :vartype azure_marketplace_service_charges: float - :ivar billing_frequency: The billing frequency. Known values are: "Month", "Quarter", "Year". + :ivar billing_frequency: The billing frequency. Known values are: "Month", "Quarter", and + "Year". :vartype billing_frequency: str or ~azure.mgmt.consumption.models.BillingFrequency :ivar price_hidden: Price is hidden or not. :vartype price_hidden: bool @@ -187,62 +176,63 @@ class Balance(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'currency': {'readonly': True}, - 'beginning_balance': {'readonly': True}, - 'ending_balance': {'readonly': True}, - 'new_purchases': {'readonly': True}, - 'adjustments': {'readonly': True}, - 'utilized': {'readonly': True}, - 'service_overage': {'readonly': True}, - 'charges_billed_separately': {'readonly': True}, - 'total_overage': {'readonly': True}, - 'total_usage': {'readonly': True}, - 'azure_marketplace_service_charges': {'readonly': True}, - 'price_hidden': {'readonly': True}, - 'new_purchases_details': {'readonly': True}, - 'adjustment_details': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "currency": {"readonly": True}, + "beginning_balance": {"readonly": True}, + "ending_balance": {"readonly": True}, + "new_purchases": {"readonly": True}, + "adjustments": {"readonly": True}, + "utilized": {"readonly": True}, + "service_overage": {"readonly": True}, + "charges_billed_separately": {"readonly": True}, + "total_overage": {"readonly": True}, + "total_usage": {"readonly": True}, + "azure_marketplace_service_charges": {"readonly": True}, + "price_hidden": {"readonly": True}, + "new_purchases_details": {"readonly": True}, + "adjustment_details": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'beginning_balance': {'key': 'properties.beginningBalance', 'type': 'float'}, - 'ending_balance': {'key': 'properties.endingBalance', 'type': 'float'}, - 'new_purchases': {'key': 'properties.newPurchases', 'type': 'float'}, - 'adjustments': {'key': 'properties.adjustments', 'type': 'float'}, - 'utilized': {'key': 'properties.utilized', 'type': 'float'}, - 'service_overage': {'key': 'properties.serviceOverage', 'type': 'float'}, - 'charges_billed_separately': {'key': 'properties.chargesBilledSeparately', 'type': 'float'}, - 'total_overage': {'key': 'properties.totalOverage', 'type': 'float'}, - 'total_usage': {'key': 'properties.totalUsage', 'type': 'float'}, - 'azure_marketplace_service_charges': {'key': 'properties.azureMarketplaceServiceCharges', 'type': 'float'}, - 'billing_frequency': {'key': 'properties.billingFrequency', 'type': 'str'}, - 'price_hidden': {'key': 'properties.priceHidden', 'type': 'bool'}, - 'new_purchases_details': {'key': 'properties.newPurchasesDetails', 'type': '[BalancePropertiesNewPurchasesDetailsItem]'}, - 'adjustment_details': {'key': 'properties.adjustmentDetails', 'type': '[BalancePropertiesAdjustmentDetailsItem]'}, - } - - def __init__( - self, - *, - billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, - **kwargs - ): - """ - :keyword billing_frequency: The billing frequency. Known values are: "Month", "Quarter", + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "currency": {"key": "properties.currency", "type": "str"}, + "beginning_balance": {"key": "properties.beginningBalance", "type": "float"}, + "ending_balance": {"key": "properties.endingBalance", "type": "float"}, + "new_purchases": {"key": "properties.newPurchases", "type": "float"}, + "adjustments": {"key": "properties.adjustments", "type": "float"}, + "utilized": {"key": "properties.utilized", "type": "float"}, + "service_overage": {"key": "properties.serviceOverage", "type": "float"}, + "charges_billed_separately": {"key": "properties.chargesBilledSeparately", "type": "float"}, + "total_overage": {"key": "properties.totalOverage", "type": "float"}, + "total_usage": {"key": "properties.totalUsage", "type": "float"}, + "azure_marketplace_service_charges": {"key": "properties.azureMarketplaceServiceCharges", "type": "float"}, + "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, + "price_hidden": {"key": "properties.priceHidden", "type": "bool"}, + "new_purchases_details": { + "key": "properties.newPurchasesDetails", + "type": "[BalancePropertiesNewPurchasesDetailsItem]", + }, + "adjustment_details": { + "key": "properties.adjustmentDetails", + "type": "[BalancePropertiesAdjustmentDetailsItem]", + }, + } + + def __init__(self, *, billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, **kwargs): + """ + :keyword billing_frequency: The billing frequency. Known values are: "Month", "Quarter", and "Year". :paramtype billing_frequency: str or ~azure.mgmt.consumption.models.BillingFrequency """ - super(Balance, self).__init__(**kwargs) + super().__init__(**kwargs) self.currency = None self.beginning_balance = None self.ending_balance = None @@ -260,7 +250,7 @@ def __init__( self.adjustment_details = None -class BalancePropertiesAdjustmentDetailsItem(msrest.serialization.Model): +class BalancePropertiesAdjustmentDetailsItem(_serialization.Model): """BalancePropertiesAdjustmentDetailsItem. Variables are only populated by the server, and will be ignored when sending a request. @@ -272,27 +262,23 @@ class BalancePropertiesAdjustmentDetailsItem(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'value': {'readonly': True}, + "name": {"readonly": True}, + "value": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "float"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(BalancePropertiesAdjustmentDetailsItem, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.value = None -class BalancePropertiesNewPurchasesDetailsItem(msrest.serialization.Model): +class BalancePropertiesNewPurchasesDetailsItem(_serialization.Model): """BalancePropertiesNewPurchasesDetailsItem. Variables are only populated by the server, and will be ignored when sending a request. @@ -304,27 +290,23 @@ class BalancePropertiesNewPurchasesDetailsItem(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'value': {'readonly': True}, + "name": {"readonly": True}, + "value": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "float"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(BalancePropertiesNewPurchasesDetailsItem, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.value = None -class ProxyResource(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. @@ -341,37 +323,32 @@ class ProxyResource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - '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"}, } - def __init__( - self, - *, - e_tag: Optional[str] = None, - **kwargs - ): + 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(ProxyResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.type = None self.e_tag = e_tag -class Budget(ProxyResource): +class Budget(ProxyResource): # pylint: disable=too-many-instance-attributes """A budget resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -385,15 +362,14 @@ class Budget(ProxyResource): :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 category: The category of the budget, whether the budget tracks cost or usage. Known - values are: "Cost". + :ivar category: The category of the budget, whether the budget tracks cost or usage. "Cost" :vartype category: str or ~azure.mgmt.consumption.models.CategoryType :ivar amount: The total amount of cost to track with the budget. :vartype amount: float :ivar time_grain: The time covered by a budget. Tracking of the amount will be reset based on the time grain. BillingMonth, BillingQuarter, and BillingAnnual are only supported by WD customers. Known values are: "Monthly", "Quarterly", "Annually", "BillingMonth", - "BillingQuarter", "BillingAnnual". + "BillingQuarter", and "BillingAnnual". :vartype time_grain: str or ~azure.mgmt.consumption.models.TimeGrainType :ivar time_period: Has start and end date of the budget. The start date must be first of the month and should be less than the end date. Budget start date must be on or after June 1, 2017. @@ -412,26 +388,26 @@ class Budget(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'current_spend': {'readonly': True}, - 'forecast_spend': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "current_spend": {"readonly": True}, + "forecast_spend": {"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'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'amount': {'key': 'properties.amount', 'type': 'float'}, - 'time_grain': {'key': 'properties.timeGrain', 'type': 'str'}, - 'time_period': {'key': 'properties.timePeriod', 'type': 'BudgetTimePeriod'}, - 'filter': {'key': 'properties.filter', 'type': 'BudgetFilter'}, - 'current_spend': {'key': 'properties.currentSpend', 'type': 'CurrentSpend'}, - 'notifications': {'key': 'properties.notifications', 'type': '{Notification}'}, - 'forecast_spend': {'key': 'properties.forecastSpend', 'type': 'ForecastSpend'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "category": {"key": "properties.category", "type": "str"}, + "amount": {"key": "properties.amount", "type": "float"}, + "time_grain": {"key": "properties.timeGrain", "type": "str"}, + "time_period": {"key": "properties.timePeriod", "type": "BudgetTimePeriod"}, + "filter": {"key": "properties.filter", "type": "BudgetFilter"}, + "current_spend": {"key": "properties.currentSpend", "type": "CurrentSpend"}, + "notifications": {"key": "properties.notifications", "type": "{Notification}"}, + "forecast_spend": {"key": "properties.forecastSpend", "type": "ForecastSpend"}, } def __init__( @@ -442,7 +418,7 @@ def __init__( amount: Optional[float] = None, time_grain: Optional[Union[str, "_models.TimeGrainType"]] = None, time_period: Optional["_models.BudgetTimePeriod"] = None, - filter: Optional["_models.BudgetFilter"] = None, + filter: Optional["_models.BudgetFilter"] = None, # pylint: disable=redefined-builtin notifications: Optional[Dict[str, "_models.Notification"]] = None, **kwargs ): @@ -450,15 +426,14 @@ def __init__( :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 category: The category of the budget, whether the budget tracks cost or usage. Known - values are: "Cost". + :keyword category: The category of the budget, whether the budget tracks cost or usage. "Cost" :paramtype category: str or ~azure.mgmt.consumption.models.CategoryType :keyword amount: The total amount of cost to track with the budget. :paramtype amount: float :keyword time_grain: The time covered by a budget. Tracking of the amount will be reset based on the time grain. BillingMonth, BillingQuarter, and BillingAnnual are only supported by WD customers. Known values are: "Monthly", "Quarterly", "Annually", "BillingMonth", - "BillingQuarter", "BillingAnnual". + "BillingQuarter", and "BillingAnnual". :paramtype time_grain: str or ~azure.mgmt.consumption.models.TimeGrainType :keyword time_period: Has start and end date of the budget. The start date must be first of the month and should be less than the end date. Budget start date must be on or after June 1, 2017. @@ -471,7 +446,7 @@ def __init__( up to five notifications. :paramtype notifications: dict[str, ~azure.mgmt.consumption.models.Notification] """ - super(Budget, self).__init__(e_tag=e_tag, **kwargs) + super().__init__(e_tag=e_tag, **kwargs) self.category = category self.amount = amount self.time_grain = time_grain @@ -482,68 +457,61 @@ def __init__( self.forecast_spend = None -class BudgetComparisonExpression(msrest.serialization.Model): +class BudgetComparisonExpression(_serialization.Model): """The comparison expression to be used in the budgets. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the column to use in comparison. + :ivar name: The name of the column to use in comparison. Required. :vartype name: str - :ivar operator: Required. The operator to use for comparison. Known values are: "In". + :ivar operator: The operator to use for comparison. Required. "In" :vartype operator: str or ~azure.mgmt.consumption.models.BudgetOperatorType - :ivar values: Required. Array of values to use for comparison. + :ivar values: Array of values to use for comparison. Required. :vartype values: list[str] """ _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True}, + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, } - def __init__( - self, - *, - name: str, - operator: Union[str, "_models.BudgetOperatorType"], - values: List[str], - **kwargs - ): + def __init__(self, *, name: str, operator: Union[str, "_models.BudgetOperatorType"], values: List[str], **kwargs): """ - :keyword name: Required. The name of the column to use in comparison. + :keyword name: The name of the column to use in comparison. Required. :paramtype name: str - :keyword operator: Required. The operator to use for comparison. Known values are: "In". + :keyword operator: The operator to use for comparison. Required. "In" :paramtype operator: str or ~azure.mgmt.consumption.models.BudgetOperatorType - :keyword values: Required. Array of values to use for comparison. + :keyword values: Array of values to use for comparison. Required. :paramtype values: list[str] """ - super(BudgetComparisonExpression, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.operator = operator self.values = values -class BudgetFilter(msrest.serialization.Model): +class BudgetFilter(_serialization.Model): """May be used to filter budgets by resource group, resource, or meter. :ivar and_property: The logical "AND" expression. Must have at least 2 items. :vartype and_property: list[~azure.mgmt.consumption.models.BudgetFilterProperties] :ivar dimensions: Has comparison expression for a dimension. :vartype dimensions: ~azure.mgmt.consumption.models.BudgetComparisonExpression - :ivar tags: A set of tags. Has comparison expression for a tag. + :ivar tags: Has comparison expression for a tag. :vartype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression """ _attribute_map = { - 'and_property': {'key': 'and', 'type': '[BudgetFilterProperties]'}, - 'dimensions': {'key': 'dimensions', 'type': 'BudgetComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'BudgetComparisonExpression'}, + "and_property": {"key": "and", "type": "[BudgetFilterProperties]"}, + "dimensions": {"key": "dimensions", "type": "BudgetComparisonExpression"}, + "tags": {"key": "tags", "type": "BudgetComparisonExpression"}, } def __init__( @@ -559,27 +527,27 @@ def __init__( :paramtype and_property: list[~azure.mgmt.consumption.models.BudgetFilterProperties] :keyword dimensions: Has comparison expression for a dimension. :paramtype dimensions: ~azure.mgmt.consumption.models.BudgetComparisonExpression - :keyword tags: A set of tags. Has comparison expression for a tag. + :keyword tags: Has comparison expression for a tag. :paramtype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression """ - super(BudgetFilter, self).__init__(**kwargs) + super().__init__(**kwargs) self.and_property = and_property self.dimensions = dimensions self.tags = tags -class BudgetFilterProperties(msrest.serialization.Model): +class BudgetFilterProperties(_serialization.Model): """The Dimensions or Tags to filter a budget by. :ivar dimensions: Has comparison expression for a dimension. :vartype dimensions: ~azure.mgmt.consumption.models.BudgetComparisonExpression - :ivar tags: A set of tags. Has comparison expression for a tag. + :ivar tags: Has comparison expression for a tag. :vartype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression """ _attribute_map = { - 'dimensions': {'key': 'dimensions', 'type': 'BudgetComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'BudgetComparisonExpression'}, + "dimensions": {"key": "dimensions", "type": "BudgetComparisonExpression"}, + "tags": {"key": "tags", "type": "BudgetComparisonExpression"}, } def __init__( @@ -592,15 +560,15 @@ def __init__( """ :keyword dimensions: Has comparison expression for a dimension. :paramtype dimensions: ~azure.mgmt.consumption.models.BudgetComparisonExpression - :keyword tags: A set of tags. Has comparison expression for a tag. + :keyword tags: Has comparison expression for a tag. :paramtype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression """ - super(BudgetFilterProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.dimensions = dimensions self.tags = tags -class BudgetsListResult(msrest.serialization.Model): +class BudgetsListResult(_serialization.Model): """Result of listing budgets. It contains a list of available budgets in the scope provided. Variables are only populated by the server, and will be ignored when sending a request. @@ -612,32 +580,28 @@ class BudgetsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Budget]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Budget]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(BudgetsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class BudgetTimePeriod(msrest.serialization.Model): +class BudgetTimePeriod(_serialization.Model): """The start and end date for a budget. All required parameters must be populated in order to send to Azure. - :ivar start_date: Required. The start date for the budget. + :ivar start_date: The start date for the budget. Required. :vartype start_date: ~datetime.datetime :ivar end_date: The end date for the budget. If not provided, we default this to 10 years from the start date. @@ -645,34 +609,28 @@ class BudgetTimePeriod(msrest.serialization.Model): """ _validation = { - 'start_date': {'required': True}, + "start_date": {"required": True}, } _attribute_map = { - 'start_date': {'key': 'startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'endDate', 'type': 'iso-8601'}, + "start_date": {"key": "startDate", "type": "iso-8601"}, + "end_date": {"key": "endDate", "type": "iso-8601"}, } - def __init__( - self, - *, - start_date: datetime.datetime, - end_date: Optional[datetime.datetime] = None, - **kwargs - ): + def __init__(self, *, start_date: datetime.datetime, end_date: Optional[datetime.datetime] = None, **kwargs): """ - :keyword start_date: Required. The start date for the budget. + :keyword start_date: The start date for the budget. Required. :paramtype start_date: ~datetime.datetime :keyword end_date: The end date for the budget. If not provided, we default this to 10 years from the start date. :paramtype end_date: ~datetime.datetime """ - super(BudgetTimePeriod, self).__init__(**kwargs) + super().__init__(**kwargs) self.start_date = start_date self.end_date = end_date -class ChargesListResult(msrest.serialization.Model): +class ChargesListResult(_serialization.Model): """Result of listing charge summary. Variables are only populated by the server, and will be ignored when sending a request. @@ -682,82 +640,71 @@ class ChargesListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, + "value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ChargeSummary]'}, + "value": {"key": "value", "type": "[ChargeSummary]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ChargesListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None -class ChargeSummary(ProxyResource): +class ChargeSummary(Resource): """A charge summary resource. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: LegacyChargeSummary, ModernChargeSummary. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LegacyChargeSummary, ModernChargeSummary 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 id: Resource Id. + :ivar id: The full qualified ARM ID of an event. :vartype id: str - :ivar name: Resource name. + :ivar name: The ID that uniquely identifies an event. :vartype name: str :ivar type: Resource type. :vartype type: 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 kind: Required. Specifies the kind of charge summary.Constant filled by server. Known - values are: "legacy", "modern". + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Specifies the kind of charge summary. Required. Known values are: "legacy" and + "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ChargeSummaryKind """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'kind': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, } - _subtype_map = { - 'kind': {'legacy': 'LegacyChargeSummary', 'modern': 'ModernChargeSummary'} - } + _subtype_map = {"kind": {"legacy": "LegacyChargeSummary", "modern": "ModernChargeSummary"}} - 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(ChargeSummary, self).__init__(e_tag=e_tag, **kwargs) - self.kind = 'ChargeSummary' # type: str + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.kind: Optional[str] = None -class CreditBalanceSummary(msrest.serialization.Model): +class CreditBalanceSummary(_serialization.Model): """Summary of credit balances. Variables are only populated by the server, and will be ignored when sending a request. @@ -772,44 +719,42 @@ class CreditBalanceSummary(msrest.serialization.Model): """ _validation = { - 'estimated_balance': {'readonly': True}, - 'current_balance': {'readonly': True}, - 'estimated_balance_in_billing_currency': {'readonly': True}, + "estimated_balance": {"readonly": True}, + "current_balance": {"readonly": True}, + "estimated_balance_in_billing_currency": {"readonly": True}, } _attribute_map = { - 'estimated_balance': {'key': 'estimatedBalance', 'type': 'Amount'}, - 'current_balance': {'key': 'currentBalance', 'type': 'Amount'}, - 'estimated_balance_in_billing_currency': {'key': 'estimatedBalanceInBillingCurrency', 'type': 'AmountWithExchangeRate'}, + "estimated_balance": {"key": "estimatedBalance", "type": "Amount"}, + "current_balance": {"key": "currentBalance", "type": "Amount"}, + "estimated_balance_in_billing_currency": { + "key": "estimatedBalanceInBillingCurrency", + "type": "AmountWithExchangeRate", + }, } - def __init__( - self, - **kwargs - ): - """ - """ - super(CreditBalanceSummary, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.estimated_balance = None self.current_balance = None self.estimated_balance_in_billing_currency = None -class CreditSummary(Resource): +class CreditSummary(ProxyResource): # pylint: disable=too-many-instance-attributes """A credit summary resource. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: The full qualified ARM ID of an event. + :ivar id: Resource Id. :vartype id: str - :ivar name: The ID that uniquely identifies an event. + :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: 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 :ivar balance_summary: Summary of balances associated with this credit summary. :vartype balance_summary: ~azure.mgmt.consumption.models.CreditBalanceSummary :ivar pending_credit_adjustments: Pending credit adjustments. @@ -824,49 +769,46 @@ class CreditSummary(Resource): :vartype billing_currency: str :ivar reseller: Credit's reseller. :vartype reseller: ~azure.mgmt.consumption.models.Reseller - :ivar e_tag: The eTag for the resource. - :vartype e_tag: str + :ivar e_tag_properties_e_tag: The eTag for the resource. + :vartype e_tag_properties_e_tag: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'balance_summary': {'readonly': True}, - 'pending_credit_adjustments': {'readonly': True}, - 'expired_credit': {'readonly': True}, - 'pending_eligible_charges': {'readonly': True}, - 'credit_currency': {'readonly': True}, - 'billing_currency': {'readonly': True}, - 'reseller': {'readonly': True}, - 'e_tag': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "balance_summary": {"readonly": True}, + "pending_credit_adjustments": {"readonly": True}, + "expired_credit": {"readonly": True}, + "pending_eligible_charges": {"readonly": True}, + "credit_currency": {"readonly": True}, + "billing_currency": {"readonly": True}, + "reseller": {"readonly": True}, + "e_tag_properties_e_tag": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'balance_summary': {'key': 'properties.balanceSummary', 'type': 'CreditBalanceSummary'}, - 'pending_credit_adjustments': {'key': 'properties.pendingCreditAdjustments', 'type': 'Amount'}, - 'expired_credit': {'key': 'properties.expiredCredit', 'type': 'Amount'}, - 'pending_eligible_charges': {'key': 'properties.pendingEligibleCharges', 'type': 'Amount'}, - 'credit_currency': {'key': 'properties.creditCurrency', 'type': 'str'}, - 'billing_currency': {'key': 'properties.billingCurrency', 'type': 'str'}, - 'reseller': {'key': 'properties.reseller', 'type': 'Reseller'}, - 'e_tag': {'key': 'properties.eTag', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "balance_summary": {"key": "properties.balanceSummary", "type": "CreditBalanceSummary"}, + "pending_credit_adjustments": {"key": "properties.pendingCreditAdjustments", "type": "Amount"}, + "expired_credit": {"key": "properties.expiredCredit", "type": "Amount"}, + "pending_eligible_charges": {"key": "properties.pendingEligibleCharges", "type": "Amount"}, + "credit_currency": {"key": "properties.creditCurrency", "type": "str"}, + "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, + "reseller": {"key": "properties.reseller", "type": "Reseller"}, + "e_tag_properties_e_tag": {"key": "properties.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(CreditSummary, self).__init__(**kwargs) + super().__init__(e_tag=e_tag, **kwargs) self.balance_summary = None self.pending_credit_adjustments = None self.expired_credit = None @@ -874,10 +816,10 @@ def __init__( self.credit_currency = None self.billing_currency = None self.reseller = None - self.e_tag = None + self.e_tag_properties_e_tag = None -class CurrentSpend(msrest.serialization.Model): +class CurrentSpend(_serialization.Model): """The current amount of cost which is being tracked for a budget. Variables are only populated by the server, and will be ignored when sending a request. @@ -889,27 +831,23 @@ class CurrentSpend(msrest.serialization.Model): """ _validation = { - 'amount': {'readonly': True}, - 'unit': {'readonly': True}, + "amount": {"readonly": True}, + "unit": {"readonly": True}, } _attribute_map = { - 'amount': {'key': 'amount', 'type': 'float'}, - 'unit': {'key': 'unit', 'type': 'str'}, + "amount": {"key": "amount", "type": "float"}, + "unit": {"key": "unit", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(CurrentSpend, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.amount = None self.unit = None -class DownloadProperties(msrest.serialization.Model): +class DownloadProperties(_serialization.Model): """The properties of the price sheet download. Variables are only populated by the server, and will be ignored when sending a request. @@ -921,27 +859,23 @@ class DownloadProperties(msrest.serialization.Model): """ _validation = { - 'download_url': {'readonly': True}, - 'valid_till': {'readonly': True}, + "download_url": {"readonly": True}, + "valid_till": {"readonly": True}, } _attribute_map = { - 'download_url': {'key': 'downloadUrl', 'type': 'str'}, - 'valid_till': {'key': 'validTill', 'type': 'str'}, + "download_url": {"key": "downloadUrl", "type": "str"}, + "valid_till": {"key": "validTill", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(DownloadProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.download_url = None self.valid_till = None -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. @@ -953,61 +887,52 @@ 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. - :ivar error: The details of the error. - :vartype error: ~azure.mgmt.consumption.models.ErrorDetails + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.consumption.models.ErrorDetails """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, + "error": {"key": "error", "type": "ErrorDetails"}, } - def __init__( - self, - *, - error: Optional["_models.ErrorDetails"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.consumption.models.ErrorDetails """ - super(ErrorResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error -class Events(msrest.serialization.Model): +class Events(_serialization.Model): """Result of listing event summary. Variables are only populated by the server, and will be ignored when sending a request. @@ -1019,27 +944,23 @@ class Events(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[EventSummary]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[EventSummary]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Events, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class EventSummary(ProxyResource): +class EventSummary(ProxyResource): # pylint: disable=too-many-instance-attributes """An event summary resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1072,7 +993,7 @@ class EventSummary(ProxyResource): :vartype closed_balance: ~azure.mgmt.consumption.models.Amount :ivar event_type: Identifies the type of the event. Known values are: "SettledCharges", "PendingCharges", "PendingAdjustments", "PendingNewCredit", "PendingExpiredCredit", "UnKnown", - "NewCredit", "CreditExpired". + "NewCredit", and "CreditExpired". :vartype event_type: str or ~azure.mgmt.consumption.models.EventType :ivar invoice_number: The number which uniquely identifies the invoice on which the event was billed. This will be empty for unbilled events. @@ -1117,69 +1038,77 @@ class EventSummary(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'transaction_date': {'readonly': True}, - 'description': {'readonly': True}, - 'new_credit': {'readonly': True}, - 'adjustments': {'readonly': True}, - 'credit_expired': {'readonly': True}, - 'charges': {'readonly': True}, - 'closed_balance': {'readonly': True}, - 'invoice_number': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'lot_id': {'readonly': True}, - 'lot_source': {'readonly': True}, - 'canceled_credit': {'readonly': True}, - 'credit_currency': {'readonly': True}, - 'billing_currency': {'readonly': True}, - 'reseller': {'readonly': True}, - 'credit_expired_in_billing_currency': {'readonly': True}, - 'new_credit_in_billing_currency': {'readonly': True}, - 'adjustments_in_billing_currency': {'readonly': True}, - 'charges_in_billing_currency': {'readonly': True}, - 'closed_balance_in_billing_currency': {'readonly': True}, - 'e_tag_properties_e_tag': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "transaction_date": {"readonly": True}, + "description": {"readonly": True}, + "new_credit": {"readonly": True}, + "adjustments": {"readonly": True}, + "credit_expired": {"readonly": True}, + "charges": {"readonly": True}, + "closed_balance": {"readonly": True}, + "invoice_number": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, + "lot_id": {"readonly": True}, + "lot_source": {"readonly": True}, + "canceled_credit": {"readonly": True}, + "credit_currency": {"readonly": True}, + "billing_currency": {"readonly": True}, + "reseller": {"readonly": True}, + "credit_expired_in_billing_currency": {"readonly": True}, + "new_credit_in_billing_currency": {"readonly": True}, + "adjustments_in_billing_currency": {"readonly": True}, + "charges_in_billing_currency": {"readonly": True}, + "closed_balance_in_billing_currency": {"readonly": True}, + "e_tag_properties_e_tag": {"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'}, - 'transaction_date': {'key': 'properties.transactionDate', 'type': 'iso-8601'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'new_credit': {'key': 'properties.newCredit', 'type': 'Amount'}, - 'adjustments': {'key': 'properties.adjustments', 'type': 'Amount'}, - 'credit_expired': {'key': 'properties.creditExpired', 'type': 'Amount'}, - 'charges': {'key': 'properties.charges', 'type': 'Amount'}, - 'closed_balance': {'key': 'properties.closedBalance', 'type': 'Amount'}, - 'event_type': {'key': 'properties.eventType', 'type': 'str'}, - 'invoice_number': {'key': 'properties.invoiceNumber', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'lot_id': {'key': 'properties.lotId', 'type': 'str'}, - 'lot_source': {'key': 'properties.lotSource', 'type': 'str'}, - 'canceled_credit': {'key': 'properties.canceledCredit', 'type': 'Amount'}, - 'credit_currency': {'key': 'properties.creditCurrency', 'type': 'str'}, - 'billing_currency': {'key': 'properties.billingCurrency', 'type': 'str'}, - 'reseller': {'key': 'properties.reseller', 'type': 'Reseller'}, - 'credit_expired_in_billing_currency': {'key': 'properties.creditExpiredInBillingCurrency', 'type': 'AmountWithExchangeRate'}, - 'new_credit_in_billing_currency': {'key': 'properties.newCreditInBillingCurrency', 'type': 'AmountWithExchangeRate'}, - 'adjustments_in_billing_currency': {'key': 'properties.adjustmentsInBillingCurrency', 'type': 'AmountWithExchangeRate'}, - 'charges_in_billing_currency': {'key': 'properties.chargesInBillingCurrency', 'type': 'AmountWithExchangeRate'}, - 'closed_balance_in_billing_currency': {'key': 'properties.closedBalanceInBillingCurrency', 'type': 'AmountWithExchangeRate'}, - 'e_tag_properties_e_tag': {'key': 'properties.eTag', 'type': 'str'}, - } - - def __init__( - self, - *, - e_tag: Optional[str] = None, - event_type: Optional[Union[str, "_models.EventType"]] = None, - **kwargs + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "transaction_date": {"key": "properties.transactionDate", "type": "iso-8601"}, + "description": {"key": "properties.description", "type": "str"}, + "new_credit": {"key": "properties.newCredit", "type": "Amount"}, + "adjustments": {"key": "properties.adjustments", "type": "Amount"}, + "credit_expired": {"key": "properties.creditExpired", "type": "Amount"}, + "charges": {"key": "properties.charges", "type": "Amount"}, + "closed_balance": {"key": "properties.closedBalance", "type": "Amount"}, + "event_type": {"key": "properties.eventType", "type": "str"}, + "invoice_number": {"key": "properties.invoiceNumber", "type": "str"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, + "lot_id": {"key": "properties.lotId", "type": "str"}, + "lot_source": {"key": "properties.lotSource", "type": "str"}, + "canceled_credit": {"key": "properties.canceledCredit", "type": "Amount"}, + "credit_currency": {"key": "properties.creditCurrency", "type": "str"}, + "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, + "reseller": {"key": "properties.reseller", "type": "Reseller"}, + "credit_expired_in_billing_currency": { + "key": "properties.creditExpiredInBillingCurrency", + "type": "AmountWithExchangeRate", + }, + "new_credit_in_billing_currency": { + "key": "properties.newCreditInBillingCurrency", + "type": "AmountWithExchangeRate", + }, + "adjustments_in_billing_currency": { + "key": "properties.adjustmentsInBillingCurrency", + "type": "AmountWithExchangeRate", + }, + "charges_in_billing_currency": {"key": "properties.chargesInBillingCurrency", "type": "AmountWithExchangeRate"}, + "closed_balance_in_billing_currency": { + "key": "properties.closedBalanceInBillingCurrency", + "type": "AmountWithExchangeRate", + }, + "e_tag_properties_e_tag": {"key": "properties.eTag", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals + self, *, e_tag: Optional[str] = None, event_type: Optional[Union[str, "_models.EventType"]] = None, **kwargs ): """ :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be @@ -1187,10 +1116,10 @@ def __init__( :paramtype e_tag: str :keyword event_type: Identifies the type of the event. Known values are: "SettledCharges", "PendingCharges", "PendingAdjustments", "PendingNewCredit", "PendingExpiredCredit", "UnKnown", - "NewCredit", "CreditExpired". + "NewCredit", and "CreditExpired". :paramtype event_type: str or ~azure.mgmt.consumption.models.EventType """ - super(EventSummary, self).__init__(e_tag=e_tag, **kwargs) + super().__init__(e_tag=e_tag, **kwargs) self.transaction_date = None self.description = None self.new_credit = None @@ -1216,7 +1145,7 @@ def __init__( self.e_tag_properties_e_tag = None -class ForecastSpend(msrest.serialization.Model): +class ForecastSpend(_serialization.Model): """The forecasted cost which is being tracked for a budget. Variables are only populated by the server, and will be ignored when sending a request. @@ -1229,27 +1158,23 @@ class ForecastSpend(msrest.serialization.Model): """ _validation = { - 'amount': {'readonly': True}, - 'unit': {'readonly': True}, + "amount": {"readonly": True}, + "unit": {"readonly": True}, } _attribute_map = { - 'amount': {'key': 'amount', 'type': 'float'}, - 'unit': {'key': 'unit', 'type': 'str'}, + "amount": {"key": "amount", "type": "float"}, + "unit": {"key": "unit", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ForecastSpend, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.amount = None self.unit = None -class HighCasedErrorDetails(msrest.serialization.Model): +class HighCasedErrorDetails(_serialization.Model): """The details of the error. Variables are only populated by the server, and will be ignored when sending a request. @@ -1261,78 +1186,70 @@ class HighCasedErrorDetails(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(HighCasedErrorDetails, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None -class HighCasedErrorResponse(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 HighCasedErrorResponse(_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. - :ivar error: The details of the error. - :vartype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails """ _attribute_map = { - 'error': {'key': 'error', 'type': 'HighCasedErrorDetails'}, + "error": {"key": "error", "type": "HighCasedErrorDetails"}, } - def __init__( - self, - *, - error: Optional["_models.HighCasedErrorDetails"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.HighCasedErrorDetails"] = None, **kwargs): """ :keyword error: The details of the error. :paramtype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails """ - super(HighCasedErrorResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error -class LegacyChargeSummary(ChargeSummary): +class LegacyChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-attributes """Legacy charge summary. 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 id: Resource Id. + :ivar id: The full qualified ARM ID of an event. :vartype id: str - :ivar name: Resource name. + :ivar name: The ID that uniquely identifies an event. :vartype name: str :ivar type: Resource type. :vartype type: 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 kind: Required. Specifies the kind of charge summary.Constant filled by server. Known - values are: "legacy", "modern". + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Specifies the kind of charge summary. Required. Known values are: "legacy" and + "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ChargeSummaryKind :ivar billing_period_id: The id of the billing period resource that the charge belongs to. :vartype billing_period_id: str @@ -1344,64 +1261,58 @@ class LegacyChargeSummary(ChargeSummary): :vartype azure_charges: float :ivar charges_billed_separately: Charges Billed separately. :vartype charges_billed_separately: float - :ivar marketplace_charges: Marketplace Charges. - :vartype marketplace_charges: float + :ivar azure_marketplace_charges: Marketplace Charges. + :vartype azure_marketplace_charges: float :ivar currency: Currency Code. :vartype currency: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'kind': {'required': True}, - 'billing_period_id': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'azure_charges': {'readonly': True}, - 'charges_billed_separately': {'readonly': True}, - 'marketplace_charges': {'readonly': True}, - 'currency': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, + "billing_period_id": {"readonly": True}, + "usage_start": {"readonly": True}, + "usage_end": {"readonly": True}, + "azure_charges": {"readonly": True}, + "charges_billed_separately": {"readonly": True}, + "azure_marketplace_charges": {"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'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'billing_period_id': {'key': 'properties.billingPeriodId', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'str'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'str'}, - 'azure_charges': {'key': 'properties.azureCharges', 'type': 'float'}, - 'charges_billed_separately': {'key': 'properties.chargesBilledSeparately', 'type': 'float'}, - 'marketplace_charges': {'key': 'properties.marketplaceCharges', 'type': 'float'}, - 'currency': {'key': 'properties.currency', '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(LegacyChargeSummary, self).__init__(e_tag=e_tag, **kwargs) - self.kind = 'legacy' # type: str + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "billing_period_id": {"key": "properties.billingPeriodId", "type": "str"}, + "usage_start": {"key": "properties.usageStart", "type": "str"}, + "usage_end": {"key": "properties.usageEnd", "type": "str"}, + "azure_charges": {"key": "properties.azureCharges", "type": "float"}, + "charges_billed_separately": {"key": "properties.chargesBilledSeparately", "type": "float"}, + "azure_marketplace_charges": {"key": "properties.azureMarketplaceCharges", "type": "float"}, + "currency": {"key": "properties.currency", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.kind: str = "legacy" self.billing_period_id = None self.usage_start = None self.usage_end = None self.azure_charges = None self.charges_billed_separately = None - self.marketplace_charges = None + self.azure_marketplace_charges = None self.currency = None -class ResourceAttributes(msrest.serialization.Model): +class ResourceAttributes(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -1413,22 +1324,18 @@ class ResourceAttributes(msrest.serialization.Model): """ _validation = { - 'location': {'readonly': True}, - 'sku': {'readonly': True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, } _attribute_map = { - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ResourceAttributes, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.location = None self.sku = None @@ -1436,8 +1343,8 @@ def __init__( class ReservationRecommendation(Resource, ResourceAttributes): """A reservation recommendation resource. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: LegacyReservationRecommendation, ModernReservationRecommendation. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LegacyReservationRecommendation, ModernReservationRecommendation Variables are only populated by the server, and will be ignored when sending a request. @@ -1455,49 +1362,43 @@ class ReservationRecommendation(Resource, ResourceAttributes): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar kind: Required. Specifies the kind of reservation recommendation.Constant filled by - server. Known values are: "legacy", "modern". + :ivar kind: Specifies the kind of reservation recommendation. Required. Known values are: + "legacy" and "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ReservationRecommendationKind """ _validation = { - 'location': {'readonly': True}, - 'sku': {'readonly': True}, - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'kind': {'required': True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, } _attribute_map = { - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'kind': {'key': 'kind', 'type': 'str'}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, } - _subtype_map = { - 'kind': {'legacy': 'LegacyReservationRecommendation', 'modern': 'ModernReservationRecommendation'} - } + _subtype_map = {"kind": {"legacy": "LegacyReservationRecommendation", "modern": "ModernReservationRecommendation"}} - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationRecommendation, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.location = None self.sku = None - self.kind = 'ReservationRecommendation' # type: str + self.kind: Optional[str] = None self.id = None self.name = None self.type = None @@ -1505,7 +1406,7 @@ def __init__( self.tags = None -class LegacyReservationRecommendation(ReservationRecommendation): +class LegacyReservationRecommendation(ReservationRecommendation): # pylint: disable=too-many-instance-attributes """Legacy reservation recommendation. Variables are only populated by the server, and will be ignored when sending a request. @@ -1524,10 +1425,10 @@ class LegacyReservationRecommendation(ReservationRecommendation): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar kind: Required. Specifies the kind of reservation recommendation.Constant filled by - server. Known values are: "legacy", "modern". + :ivar kind: Specifies the kind of reservation recommendation. Required. Known values are: + "legacy" and "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ReservationRecommendationKind :ivar look_back_period: The number of days of usage to look back for recommendation. :vartype look_back_period: str @@ -1555,72 +1456,68 @@ class LegacyReservationRecommendation(ReservationRecommendation): :vartype net_savings: float :ivar first_usage_date: The usage date for looking back. :vartype first_usage_date: ~datetime.datetime - :ivar scope: Required. Shared or single recommendation.Constant filled by server. + :ivar scope: Shared or single recommendation. Required. :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] """ _validation = { - 'location': {'readonly': True}, - 'sku': {'readonly': True}, - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'kind': {'required': True}, - 'look_back_period': {'readonly': True}, - 'instance_flexibility_ratio': {'readonly': True}, - 'instance_flexibility_group': {'readonly': True}, - 'normalized_size': {'readonly': True}, - 'recommended_quantity_normalized': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'resource_type': {'readonly': True}, - 'term': {'readonly': True}, - 'cost_with_no_reserved_instances': {'readonly': True}, - 'recommended_quantity': {'readonly': True}, - 'total_cost_with_reserved_instances': {'readonly': True}, - 'net_savings': {'readonly': True}, - 'first_usage_date': {'readonly': True}, - 'scope': {'required': True}, - 'sku_properties': {'readonly': True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "resource_type": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, } _attribute_map = { - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'look_back_period': {'key': 'properties.lookBackPeriod', 'type': 'str'}, - 'instance_flexibility_ratio': {'key': 'properties.instanceFlexibilityRatio', 'type': 'float'}, - 'instance_flexibility_group': {'key': 'properties.instanceFlexibilityGroup', 'type': 'str'}, - 'normalized_size': {'key': 'properties.normalizedSize', 'type': 'str'}, - 'recommended_quantity_normalized': {'key': 'properties.recommendedQuantityNormalized', 'type': 'float'}, - 'meter_id': {'key': 'properties.meterId', 'type': 'str'}, - 'resource_type': {'key': 'properties.resourceType', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'cost_with_no_reserved_instances': {'key': 'properties.costWithNoReservedInstances', 'type': 'float'}, - 'recommended_quantity': {'key': 'properties.recommendedQuantity', 'type': 'float'}, - 'total_cost_with_reserved_instances': {'key': 'properties.totalCostWithReservedInstances', 'type': 'float'}, - 'net_savings': {'key': 'properties.netSavings', 'type': 'float'}, - 'first_usage_date': {'key': 'properties.firstUsageDate', 'type': 'iso-8601'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'sku_properties': {'key': 'properties.skuProperties', 'type': '[SkuProperty]'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(LegacyReservationRecommendation, self).__init__(**kwargs) - self.kind = 'legacy' # type: str + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "look_back_period": {"key": "properties.lookBackPeriod", "type": "str"}, + "instance_flexibility_ratio": {"key": "properties.instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "properties.instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "properties.normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "properties.recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "properties.meterId", "type": "str"}, + "resource_type": {"key": "properties.resourceType", "type": "str"}, + "term": {"key": "properties.term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "properties.costWithNoReservedInstances", "type": "float"}, + "recommended_quantity": {"key": "properties.recommendedQuantity", "type": "float"}, + "total_cost_with_reserved_instances": {"key": "properties.totalCostWithReservedInstances", "type": "float"}, + "net_savings": {"key": "properties.netSavings", "type": "float"}, + "first_usage_date": {"key": "properties.firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "properties.scope", "type": "str"}, + "sku_properties": {"key": "properties.skuProperties", "type": "[SkuProperty]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.kind: str = "legacy" self.look_back_period = None self.instance_flexibility_ratio = None self.instance_flexibility_group = None @@ -1634,15 +1531,16 @@ def __init__( self.total_cost_with_reserved_instances = None self.net_savings = None self.first_usage_date = None - self.scope = 'legacy' # type: str + self.scope: str = "legacy" self.sku_properties = None -class LegacyReservationRecommendationProperties(msrest.serialization.Model): +class LegacyReservationRecommendationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes """The properties of the reservation recommendation. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: LegacySharedScopeReservationRecommendationProperties, LegacySingleScopeReservationRecommendationProperties. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LegacySharedScopeReservationRecommendationProperties, + LegacySingleScopeReservationRecommendationProperties Variables are only populated by the server, and will be ignored when sending a request. @@ -1674,59 +1572,58 @@ class LegacyReservationRecommendationProperties(msrest.serialization.Model): :vartype net_savings: float :ivar first_usage_date: The usage date for looking back. :vartype first_usage_date: ~datetime.datetime - :ivar scope: Required. Shared or single recommendation.Constant filled by server. + :ivar scope: Shared or single recommendation. Required. :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] """ _validation = { - 'look_back_period': {'readonly': True}, - 'instance_flexibility_ratio': {'readonly': True}, - 'instance_flexibility_group': {'readonly': True}, - 'normalized_size': {'readonly': True}, - 'recommended_quantity_normalized': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'resource_type': {'readonly': True}, - 'term': {'readonly': True}, - 'cost_with_no_reserved_instances': {'readonly': True}, - 'recommended_quantity': {'readonly': True}, - 'total_cost_with_reserved_instances': {'readonly': True}, - 'net_savings': {'readonly': True}, - 'first_usage_date': {'readonly': True}, - 'scope': {'required': True}, - 'sku_properties': {'readonly': True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "resource_type": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, } _attribute_map = { - 'look_back_period': {'key': 'lookBackPeriod', 'type': 'str'}, - 'instance_flexibility_ratio': {'key': 'instanceFlexibilityRatio', 'type': 'float'}, - 'instance_flexibility_group': {'key': 'instanceFlexibilityGroup', 'type': 'str'}, - 'normalized_size': {'key': 'normalizedSize', 'type': 'str'}, - 'recommended_quantity_normalized': {'key': 'recommendedQuantityNormalized', 'type': 'float'}, - 'meter_id': {'key': 'meterId', 'type': 'str'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'term': {'key': 'term', 'type': 'str'}, - 'cost_with_no_reserved_instances': {'key': 'costWithNoReservedInstances', 'type': 'float'}, - 'recommended_quantity': {'key': 'recommendedQuantity', 'type': 'float'}, - 'total_cost_with_reserved_instances': {'key': 'totalCostWithReservedInstances', 'type': 'float'}, - 'net_savings': {'key': 'netSavings', 'type': 'float'}, - 'first_usage_date': {'key': 'firstUsageDate', 'type': 'iso-8601'}, - 'scope': {'key': 'scope', 'type': 'str'}, - 'sku_properties': {'key': 'skuProperties', 'type': '[SkuProperty]'}, + "look_back_period": {"key": "lookBackPeriod", "type": "str"}, + "instance_flexibility_ratio": {"key": "instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "meterId", "type": "str"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "costWithNoReservedInstances", "type": "float"}, + "recommended_quantity": {"key": "recommendedQuantity", "type": "float"}, + "total_cost_with_reserved_instances": {"key": "totalCostWithReservedInstances", "type": "float"}, + "net_savings": {"key": "netSavings", "type": "float"}, + "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "scope", "type": "str"}, + "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, } _subtype_map = { - 'scope': {'Shared': 'LegacySharedScopeReservationRecommendationProperties', 'Single': 'LegacySingleScopeReservationRecommendationProperties'} + "scope": { + "Shared": "LegacySharedScopeReservationRecommendationProperties", + "Single": "LegacySingleScopeReservationRecommendationProperties", + } } - def __init__( - self, - **kwargs - ): - """ - """ - super(LegacyReservationRecommendationProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.look_back_period = None self.instance_flexibility_ratio = None self.instance_flexibility_group = None @@ -1740,11 +1637,11 @@ def __init__( self.total_cost_with_reserved_instances = None self.net_savings = None self.first_usage_date = None - self.scope = None # type: Optional[str] + self.scope: Optional[str] = None self.sku_properties = None -class ReservationTransactionResource(msrest.serialization.Model): +class ReservationTransactionResource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -1755,38 +1652,34 @@ class ReservationTransactionResource(msrest.serialization.Model): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: list[str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, + "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]'}, + "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(ReservationTransactionResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None self.tags = None -class ReservationTransaction(ReservationTransactionResource): +class ReservationTransaction(ReservationTransactionResource): # pylint: disable=too-many-instance-attributes """Reservation transaction resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1797,7 +1690,7 @@ class ReservationTransaction(ReservationTransactionResource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: list[str] :ivar event_date: The date of the transaction. :vartype event_date: ~datetime.datetime @@ -1808,7 +1701,7 @@ class ReservationTransaction(ReservationTransactionResource): :vartype reservation_order_id: str :ivar description: The description of the transaction. :vartype description: str - :ivar event_type: The type of the transaction (Purchase, Cancel, etc.). + :ivar event_type: The type of the transaction (Purchase, Cancel or Refund). :vartype event_type: str :ivar quantity: The quantity of the transaction. :vartype quantity: float @@ -1853,72 +1746,68 @@ class ReservationTransaction(ReservationTransactionResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'event_date': {'readonly': True}, - 'reservation_order_id': {'readonly': True}, - 'description': {'readonly': True}, - 'event_type': {'readonly': True}, - 'quantity': {'readonly': True}, - 'amount': {'readonly': True}, - 'currency': {'readonly': True}, - 'reservation_order_name': {'readonly': True}, - 'purchasing_enrollment': {'readonly': True}, - 'purchasing_subscription_guid': {'readonly': True}, - 'purchasing_subscription_name': {'readonly': True}, - 'arm_sku_name': {'readonly': True}, - 'term': {'readonly': True}, - 'region': {'readonly': True}, - 'account_name': {'readonly': True}, - 'account_owner_email': {'readonly': True}, - 'department_name': {'readonly': True}, - 'cost_center': {'readonly': True}, - 'current_enrollment': {'readonly': True}, - 'billing_frequency': {'readonly': True}, - 'billing_month': {'readonly': True}, - 'monetary_commitment': {'readonly': True}, - 'overage': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "tags": {"readonly": True}, + "event_date": {"readonly": True}, + "reservation_order_id": {"readonly": True}, + "description": {"readonly": True}, + "event_type": {"readonly": True}, + "quantity": {"readonly": True}, + "amount": {"readonly": True}, + "currency": {"readonly": True}, + "reservation_order_name": {"readonly": True}, + "purchasing_enrollment": {"readonly": True}, + "purchasing_subscription_guid": {"readonly": True}, + "purchasing_subscription_name": {"readonly": True}, + "arm_sku_name": {"readonly": True}, + "term": {"readonly": True}, + "region": {"readonly": True}, + "account_name": {"readonly": True}, + "account_owner_email": {"readonly": True}, + "department_name": {"readonly": True}, + "cost_center": {"readonly": True}, + "current_enrollment": {"readonly": True}, + "billing_frequency": {"readonly": True}, + "billing_month": {"readonly": True}, + "monetary_commitment": {"readonly": True}, + "overage": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '[str]'}, - 'event_date': {'key': 'properties.eventDate', 'type': 'iso-8601'}, - 'reservation_order_id': {'key': 'properties.reservationOrderId', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'event_type': {'key': 'properties.eventType', 'type': 'str'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'amount': {'key': 'properties.amount', 'type': 'float'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'reservation_order_name': {'key': 'properties.reservationOrderName', 'type': 'str'}, - 'purchasing_enrollment': {'key': 'properties.purchasingEnrollment', 'type': 'str'}, - 'purchasing_subscription_guid': {'key': 'properties.purchasingSubscriptionGuid', 'type': 'str'}, - 'purchasing_subscription_name': {'key': 'properties.purchasingSubscriptionName', 'type': 'str'}, - 'arm_sku_name': {'key': 'properties.armSkuName', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'region': {'key': 'properties.region', 'type': 'str'}, - 'account_name': {'key': 'properties.accountName', 'type': 'str'}, - 'account_owner_email': {'key': 'properties.accountOwnerEmail', 'type': 'str'}, - 'department_name': {'key': 'properties.departmentName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'current_enrollment': {'key': 'properties.currentEnrollment', 'type': 'str'}, - 'billing_frequency': {'key': 'properties.billingFrequency', 'type': 'str'}, - 'billing_month': {'key': 'properties.billingMonth', 'type': 'int'}, - 'monetary_commitment': {'key': 'properties.monetaryCommitment', 'type': 'float'}, - 'overage': {'key': 'properties.overage', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationTransaction, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "[str]"}, + "event_date": {"key": "properties.eventDate", "type": "iso-8601"}, + "reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "event_type": {"key": "properties.eventType", "type": "str"}, + "quantity": {"key": "properties.quantity", "type": "float"}, + "amount": {"key": "properties.amount", "type": "float"}, + "currency": {"key": "properties.currency", "type": "str"}, + "reservation_order_name": {"key": "properties.reservationOrderName", "type": "str"}, + "purchasing_enrollment": {"key": "properties.purchasingEnrollment", "type": "str"}, + "purchasing_subscription_guid": {"key": "properties.purchasingSubscriptionGuid", "type": "str"}, + "purchasing_subscription_name": {"key": "properties.purchasingSubscriptionName", "type": "str"}, + "arm_sku_name": {"key": "properties.armSkuName", "type": "str"}, + "term": {"key": "properties.term", "type": "str"}, + "region": {"key": "properties.region", "type": "str"}, + "account_name": {"key": "properties.accountName", "type": "str"}, + "account_owner_email": {"key": "properties.accountOwnerEmail", "type": "str"}, + "department_name": {"key": "properties.departmentName", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "current_enrollment": {"key": "properties.currentEnrollment", "type": "str"}, + "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, + "billing_month": {"key": "properties.billingMonth", "type": "int"}, + "monetary_commitment": {"key": "properties.monetaryCommitment", "type": "float"}, + "overage": {"key": "properties.overage", "type": "float"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) self.event_date = None self.reservation_order_id = None self.description = None @@ -1944,7 +1833,7 @@ def __init__( self.overage = None -class LegacyReservationTransaction(ReservationTransaction): +class LegacyReservationTransaction(ReservationTransaction): # pylint: disable=too-many-instance-attributes """Legacy Reservation transaction resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1955,7 +1844,7 @@ class LegacyReservationTransaction(ReservationTransaction): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: list[str] :ivar event_date: The date of the transaction. :vartype event_date: ~datetime.datetime @@ -1966,7 +1855,7 @@ class LegacyReservationTransaction(ReservationTransaction): :vartype reservation_order_id: str :ivar description: The description of the transaction. :vartype description: str - :ivar event_type: The type of the transaction (Purchase, Cancel, etc.). + :ivar event_type: The type of the transaction (Purchase, Cancel or Refund). :vartype event_type: str :ivar quantity: The quantity of the transaction. :vartype quantity: float @@ -2011,75 +1900,73 @@ class LegacyReservationTransaction(ReservationTransaction): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'event_date': {'readonly': True}, - 'reservation_order_id': {'readonly': True}, - 'description': {'readonly': True}, - 'event_type': {'readonly': True}, - 'quantity': {'readonly': True}, - 'amount': {'readonly': True}, - 'currency': {'readonly': True}, - 'reservation_order_name': {'readonly': True}, - 'purchasing_enrollment': {'readonly': True}, - 'purchasing_subscription_guid': {'readonly': True}, - 'purchasing_subscription_name': {'readonly': True}, - 'arm_sku_name': {'readonly': True}, - 'term': {'readonly': True}, - 'region': {'readonly': True}, - 'account_name': {'readonly': True}, - 'account_owner_email': {'readonly': True}, - 'department_name': {'readonly': True}, - 'cost_center': {'readonly': True}, - 'current_enrollment': {'readonly': True}, - 'billing_frequency': {'readonly': True}, - 'billing_month': {'readonly': True}, - 'monetary_commitment': {'readonly': True}, - 'overage': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "tags": {"readonly": True}, + "event_date": {"readonly": True}, + "reservation_order_id": {"readonly": True}, + "description": {"readonly": True}, + "event_type": {"readonly": True}, + "quantity": {"readonly": True}, + "amount": {"readonly": True}, + "currency": {"readonly": True}, + "reservation_order_name": {"readonly": True}, + "purchasing_enrollment": {"readonly": True}, + "purchasing_subscription_guid": {"readonly": True}, + "purchasing_subscription_name": {"readonly": True}, + "arm_sku_name": {"readonly": True}, + "term": {"readonly": True}, + "region": {"readonly": True}, + "account_name": {"readonly": True}, + "account_owner_email": {"readonly": True}, + "department_name": {"readonly": True}, + "cost_center": {"readonly": True}, + "current_enrollment": {"readonly": True}, + "billing_frequency": {"readonly": True}, + "billing_month": {"readonly": True}, + "monetary_commitment": {"readonly": True}, + "overage": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '[str]'}, - 'event_date': {'key': 'properties.eventDate', 'type': 'iso-8601'}, - 'reservation_order_id': {'key': 'properties.reservationOrderId', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'event_type': {'key': 'properties.eventType', 'type': 'str'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'amount': {'key': 'properties.amount', 'type': 'float'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'reservation_order_name': {'key': 'properties.reservationOrderName', 'type': 'str'}, - 'purchasing_enrollment': {'key': 'properties.purchasingEnrollment', 'type': 'str'}, - 'purchasing_subscription_guid': {'key': 'properties.purchasingSubscriptionGuid', 'type': 'str'}, - 'purchasing_subscription_name': {'key': 'properties.purchasingSubscriptionName', 'type': 'str'}, - 'arm_sku_name': {'key': 'properties.armSkuName', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'region': {'key': 'properties.region', 'type': 'str'}, - 'account_name': {'key': 'properties.accountName', 'type': 'str'}, - 'account_owner_email': {'key': 'properties.accountOwnerEmail', 'type': 'str'}, - 'department_name': {'key': 'properties.departmentName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'current_enrollment': {'key': 'properties.currentEnrollment', 'type': 'str'}, - 'billing_frequency': {'key': 'properties.billingFrequency', 'type': 'str'}, - 'billing_month': {'key': 'properties.billingMonth', 'type': 'int'}, - 'monetary_commitment': {'key': 'properties.monetaryCommitment', 'type': 'float'}, - 'overage': {'key': 'properties.overage', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(LegacyReservationTransaction, self).__init__(**kwargs) - - -class LegacySharedScopeReservationRecommendationProperties(LegacyReservationRecommendationProperties): + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "[str]"}, + "event_date": {"key": "properties.eventDate", "type": "iso-8601"}, + "reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "event_type": {"key": "properties.eventType", "type": "str"}, + "quantity": {"key": "properties.quantity", "type": "float"}, + "amount": {"key": "properties.amount", "type": "float"}, + "currency": {"key": "properties.currency", "type": "str"}, + "reservation_order_name": {"key": "properties.reservationOrderName", "type": "str"}, + "purchasing_enrollment": {"key": "properties.purchasingEnrollment", "type": "str"}, + "purchasing_subscription_guid": {"key": "properties.purchasingSubscriptionGuid", "type": "str"}, + "purchasing_subscription_name": {"key": "properties.purchasingSubscriptionName", "type": "str"}, + "arm_sku_name": {"key": "properties.armSkuName", "type": "str"}, + "term": {"key": "properties.term", "type": "str"}, + "region": {"key": "properties.region", "type": "str"}, + "account_name": {"key": "properties.accountName", "type": "str"}, + "account_owner_email": {"key": "properties.accountOwnerEmail", "type": "str"}, + "department_name": {"key": "properties.departmentName", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "current_enrollment": {"key": "properties.currentEnrollment", "type": "str"}, + "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, + "billing_month": {"key": "properties.billingMonth", "type": "int"}, + "monetary_commitment": {"key": "properties.monetaryCommitment", "type": "float"}, + "overage": {"key": "properties.overage", "type": "float"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) + + +class LegacySharedScopeReservationRecommendationProperties( + LegacyReservationRecommendationProperties +): # pylint: disable=too-many-instance-attributes """The properties of the legacy reservation recommendation for shared scope. Variables are only populated by the server, and will be ignored when sending a request. @@ -2112,60 +1999,58 @@ class LegacySharedScopeReservationRecommendationProperties(LegacyReservationReco :vartype net_savings: float :ivar first_usage_date: The usage date for looking back. :vartype first_usage_date: ~datetime.datetime - :ivar scope: Required. Shared or single recommendation.Constant filled by server. + :ivar scope: Shared or single recommendation. Required. :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] """ _validation = { - 'look_back_period': {'readonly': True}, - 'instance_flexibility_ratio': {'readonly': True}, - 'instance_flexibility_group': {'readonly': True}, - 'normalized_size': {'readonly': True}, - 'recommended_quantity_normalized': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'resource_type': {'readonly': True}, - 'term': {'readonly': True}, - 'cost_with_no_reserved_instances': {'readonly': True}, - 'recommended_quantity': {'readonly': True}, - 'total_cost_with_reserved_instances': {'readonly': True}, - 'net_savings': {'readonly': True}, - 'first_usage_date': {'readonly': True}, - 'scope': {'required': True}, - 'sku_properties': {'readonly': True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "resource_type": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, } _attribute_map = { - 'look_back_period': {'key': 'lookBackPeriod', 'type': 'str'}, - 'instance_flexibility_ratio': {'key': 'instanceFlexibilityRatio', 'type': 'float'}, - 'instance_flexibility_group': {'key': 'instanceFlexibilityGroup', 'type': 'str'}, - 'normalized_size': {'key': 'normalizedSize', 'type': 'str'}, - 'recommended_quantity_normalized': {'key': 'recommendedQuantityNormalized', 'type': 'float'}, - 'meter_id': {'key': 'meterId', 'type': 'str'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'term': {'key': 'term', 'type': 'str'}, - 'cost_with_no_reserved_instances': {'key': 'costWithNoReservedInstances', 'type': 'float'}, - 'recommended_quantity': {'key': 'recommendedQuantity', 'type': 'float'}, - 'total_cost_with_reserved_instances': {'key': 'totalCostWithReservedInstances', 'type': 'float'}, - 'net_savings': {'key': 'netSavings', 'type': 'float'}, - 'first_usage_date': {'key': 'firstUsageDate', 'type': 'iso-8601'}, - 'scope': {'key': 'scope', 'type': 'str'}, - 'sku_properties': {'key': 'skuProperties', 'type': '[SkuProperty]'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(LegacySharedScopeReservationRecommendationProperties, self).__init__(**kwargs) - self.scope = 'Shared' # type: str - - -class LegacySingleScopeReservationRecommendationProperties(LegacyReservationRecommendationProperties): - """The properties of the legacy reservation recommendation for single scope. + "look_back_period": {"key": "lookBackPeriod", "type": "str"}, + "instance_flexibility_ratio": {"key": "instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "meterId", "type": "str"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "costWithNoReservedInstances", "type": "float"}, + "recommended_quantity": {"key": "recommendedQuantity", "type": "float"}, + "total_cost_with_reserved_instances": {"key": "totalCostWithReservedInstances", "type": "float"}, + "net_savings": {"key": "netSavings", "type": "float"}, + "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "scope", "type": "str"}, + "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.scope: str = "Shared" + + +class LegacySingleScopeReservationRecommendationProperties( + LegacyReservationRecommendationProperties +): # pylint: disable=too-many-instance-attributes + """The properties of the legacy reservation recommendation for single scope. Variables are only populated by the server, and will be ignored when sending a request. @@ -2197,7 +2082,7 @@ class LegacySingleScopeReservationRecommendationProperties(LegacyReservationReco :vartype net_savings: float :ivar first_usage_date: The usage date for looking back. :vartype first_usage_date: ~datetime.datetime - :ivar scope: Required. Shared or single recommendation.Constant filled by server. + :ivar scope: Shared or single recommendation. Required. :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] @@ -2206,59 +2091,55 @@ class LegacySingleScopeReservationRecommendationProperties(LegacyReservationReco """ _validation = { - 'look_back_period': {'readonly': True}, - 'instance_flexibility_ratio': {'readonly': True}, - 'instance_flexibility_group': {'readonly': True}, - 'normalized_size': {'readonly': True}, - 'recommended_quantity_normalized': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'resource_type': {'readonly': True}, - 'term': {'readonly': True}, - 'cost_with_no_reserved_instances': {'readonly': True}, - 'recommended_quantity': {'readonly': True}, - 'total_cost_with_reserved_instances': {'readonly': True}, - 'net_savings': {'readonly': True}, - 'first_usage_date': {'readonly': True}, - 'scope': {'required': True}, - 'sku_properties': {'readonly': True}, - 'subscription_id': {'readonly': True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "resource_type": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, + "subscription_id": {"readonly": True}, } _attribute_map = { - 'look_back_period': {'key': 'lookBackPeriod', 'type': 'str'}, - 'instance_flexibility_ratio': {'key': 'instanceFlexibilityRatio', 'type': 'float'}, - 'instance_flexibility_group': {'key': 'instanceFlexibilityGroup', 'type': 'str'}, - 'normalized_size': {'key': 'normalizedSize', 'type': 'str'}, - 'recommended_quantity_normalized': {'key': 'recommendedQuantityNormalized', 'type': 'float'}, - 'meter_id': {'key': 'meterId', 'type': 'str'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'term': {'key': 'term', 'type': 'str'}, - 'cost_with_no_reserved_instances': {'key': 'costWithNoReservedInstances', 'type': 'float'}, - 'recommended_quantity': {'key': 'recommendedQuantity', 'type': 'float'}, - 'total_cost_with_reserved_instances': {'key': 'totalCostWithReservedInstances', 'type': 'float'}, - 'net_savings': {'key': 'netSavings', 'type': 'float'}, - 'first_usage_date': {'key': 'firstUsageDate', 'type': 'iso-8601'}, - 'scope': {'key': 'scope', 'type': 'str'}, - 'sku_properties': {'key': 'skuProperties', 'type': '[SkuProperty]'}, - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(LegacySingleScopeReservationRecommendationProperties, self).__init__(**kwargs) - self.scope = 'Single' # type: str + "look_back_period": {"key": "lookBackPeriod", "type": "str"}, + "instance_flexibility_ratio": {"key": "instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "meterId", "type": "str"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "costWithNoReservedInstances", "type": "float"}, + "recommended_quantity": {"key": "recommendedQuantity", "type": "float"}, + "total_cost_with_reserved_instances": {"key": "totalCostWithReservedInstances", "type": "float"}, + "net_savings": {"key": "netSavings", "type": "float"}, + "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "scope", "type": "str"}, + "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.scope: str = "Single" self.subscription_id = None class UsageDetail(Resource): """An usage detail resource. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: LegacyUsageDetail, ModernUsageDetail. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LegacyUsageDetail, ModernUsageDetail Variables are only populated by the server, and will be ignored when sending a request. @@ -2272,46 +2153,40 @@ class UsageDetail(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar kind: Required. Specifies the kind of usage details.Constant filled by server. Known - values are: "legacy", "modern". + :ivar kind: Specifies the kind of usage details. Required. Known values are: "legacy" and + "modern". :vartype kind: str or ~azure.mgmt.consumption.models.UsageDetailsKind """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'kind': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'kind': {'key': 'kind', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, } - _subtype_map = { - 'kind': {'legacy': 'LegacyUsageDetail', 'modern': 'ModernUsageDetail'} - } + _subtype_map = {"kind": {"legacy": "LegacyUsageDetail", "modern": "ModernUsageDetail"}} - def __init__( - self, - **kwargs - ): - """ - """ - super(UsageDetail, self).__init__(**kwargs) - self.kind = 'UsageDetail' # type: str + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.kind: Optional[str] = None -class LegacyUsageDetail(UsageDetail): +class LegacyUsageDetail(UsageDetail): # pylint: disable=too-many-instance-attributes """Legacy usage detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -2326,10 +2201,10 @@ class LegacyUsageDetail(UsageDetail): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar kind: Required. Specifies the kind of usage details.Constant filled by server. Known - values are: "legacy", "modern". + :ivar kind: Specifies the kind of usage details. Required. Known values are: "legacy" and + "modern". :vartype kind: str or ~azure.mgmt.consumption.models.UsageDetailsKind :ivar billing_account_id: Billing Account identifier. :vartype billing_account_id: str @@ -2439,128 +2314,124 @@ class LegacyUsageDetail(UsageDetail): :ivar benefit_name: Name of the applicable benefit. :vartype benefit_name: str :ivar pricing_model: Identifier that indicates how the meter is priced. Known values are: "On - Demand", "Reservation", "Spot". + Demand", "Reservation", and "Spot". :vartype pricing_model: str or ~azure.mgmt.consumption.models.PricingModelType """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'kind': {'required': True}, - 'billing_account_id': {'readonly': True}, - 'billing_account_name': {'readonly': True}, - 'billing_period_start_date': {'readonly': True}, - 'billing_period_end_date': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_name': {'readonly': True}, - 'account_owner_id': {'readonly': True}, - 'account_name': {'readonly': True}, - 'subscription_id': {'readonly': True}, - 'subscription_name': {'readonly': True}, - 'date': {'readonly': True}, - 'product': {'readonly': True}, - 'part_number': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'meter_details': {'readonly': True}, - 'quantity': {'readonly': True}, - 'effective_price': {'readonly': True}, - 'cost': {'readonly': True}, - 'unit_price': {'readonly': True}, - 'billing_currency': {'readonly': True}, - 'resource_location': {'readonly': True}, - 'consumed_service': {'readonly': True}, - 'resource_id': {'readonly': True}, - 'resource_name': {'readonly': True}, - 'service_info1': {'readonly': True}, - 'service_info2': {'readonly': True}, - 'additional_info': {'readonly': True}, - 'invoice_section': {'readonly': True}, - 'cost_center': {'readonly': True}, - 'resource_group': {'readonly': True}, - 'reservation_id': {'readonly': True}, - 'reservation_name': {'readonly': True}, - 'product_order_id': {'readonly': True}, - 'product_order_name': {'readonly': True}, - 'offer_id': {'readonly': True}, - 'is_azure_credit_eligible': {'readonly': True}, - 'term': {'readonly': True}, - 'publisher_name': {'readonly': True}, - 'publisher_type': {'readonly': True}, - 'plan_name': {'readonly': True}, - 'charge_type': {'readonly': True}, - 'frequency': {'readonly': True}, - 'pay_g_price': {'readonly': True}, - 'benefit_id': {'readonly': True}, - 'benefit_name': {'readonly': True}, - 'pricing_model': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, + "billing_account_id": {"readonly": True}, + "billing_account_name": {"readonly": True}, + "billing_period_start_date": {"readonly": True}, + "billing_period_end_date": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_name": {"readonly": True}, + "account_owner_id": {"readonly": True}, + "account_name": {"readonly": True}, + "subscription_id": {"readonly": True}, + "subscription_name": {"readonly": True}, + "date": {"readonly": True}, + "product": {"readonly": True}, + "part_number": {"readonly": True}, + "meter_id": {"readonly": True}, + "meter_details": {"readonly": True}, + "quantity": {"readonly": True}, + "effective_price": {"readonly": True}, + "cost": {"readonly": True}, + "unit_price": {"readonly": True}, + "billing_currency": {"readonly": True}, + "resource_location": {"readonly": True}, + "consumed_service": {"readonly": True}, + "resource_id": {"readonly": True}, + "resource_name": {"readonly": True}, + "service_info1": {"readonly": True}, + "service_info2": {"readonly": True}, + "additional_info": {"readonly": True}, + "invoice_section": {"readonly": True}, + "cost_center": {"readonly": True}, + "resource_group": {"readonly": True}, + "reservation_id": {"readonly": True}, + "reservation_name": {"readonly": True}, + "product_order_id": {"readonly": True}, + "product_order_name": {"readonly": True}, + "offer_id": {"readonly": True}, + "is_azure_credit_eligible": {"readonly": True}, + "term": {"readonly": True}, + "publisher_name": {"readonly": True}, + "publisher_type": {"readonly": True}, + "plan_name": {"readonly": True}, + "charge_type": {"readonly": True}, + "frequency": {"readonly": True}, + "pay_g_price": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_name": {"readonly": True}, + "pricing_model": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'billing_account_id': {'key': 'properties.billingAccountId', 'type': 'str'}, - 'billing_account_name': {'key': 'properties.billingAccountName', 'type': 'str'}, - 'billing_period_start_date': {'key': 'properties.billingPeriodStartDate', 'type': 'iso-8601'}, - 'billing_period_end_date': {'key': 'properties.billingPeriodEndDate', 'type': 'iso-8601'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_name': {'key': 'properties.billingProfileName', 'type': 'str'}, - 'account_owner_id': {'key': 'properties.accountOwnerId', 'type': 'str'}, - 'account_name': {'key': 'properties.accountName', 'type': 'str'}, - 'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'}, - 'subscription_name': {'key': 'properties.subscriptionName', 'type': 'str'}, - 'date': {'key': 'properties.date', 'type': 'iso-8601'}, - 'product': {'key': 'properties.product', 'type': 'str'}, - 'part_number': {'key': 'properties.partNumber', 'type': 'str'}, - 'meter_id': {'key': 'properties.meterId', 'type': 'str'}, - 'meter_details': {'key': 'properties.meterDetails', 'type': 'MeterDetailsResponse'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'effective_price': {'key': 'properties.effectivePrice', 'type': 'float'}, - 'cost': {'key': 'properties.cost', 'type': 'float'}, - 'unit_price': {'key': 'properties.unitPrice', 'type': 'float'}, - 'billing_currency': {'key': 'properties.billingCurrency', 'type': 'str'}, - 'resource_location': {'key': 'properties.resourceLocation', 'type': 'str'}, - 'consumed_service': {'key': 'properties.consumedService', 'type': 'str'}, - 'resource_id': {'key': 'properties.resourceId', 'type': 'str'}, - 'resource_name': {'key': 'properties.resourceName', 'type': 'str'}, - 'service_info1': {'key': 'properties.serviceInfo1', 'type': 'str'}, - 'service_info2': {'key': 'properties.serviceInfo2', 'type': 'str'}, - 'additional_info': {'key': 'properties.additionalInfo', 'type': 'str'}, - 'invoice_section': {'key': 'properties.invoiceSection', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'resource_group': {'key': 'properties.resourceGroup', 'type': 'str'}, - 'reservation_id': {'key': 'properties.reservationId', 'type': 'str'}, - 'reservation_name': {'key': 'properties.reservationName', 'type': 'str'}, - 'product_order_id': {'key': 'properties.productOrderId', 'type': 'str'}, - 'product_order_name': {'key': 'properties.productOrderName', 'type': 'str'}, - 'offer_id': {'key': 'properties.offerId', 'type': 'str'}, - 'is_azure_credit_eligible': {'key': 'properties.isAzureCreditEligible', 'type': 'bool'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'publisher_name': {'key': 'properties.publisherName', 'type': 'str'}, - 'publisher_type': {'key': 'properties.publisherType', 'type': 'str'}, - 'plan_name': {'key': 'properties.planName', 'type': 'str'}, - 'charge_type': {'key': 'properties.chargeType', 'type': 'str'}, - 'frequency': {'key': 'properties.frequency', 'type': 'str'}, - 'pay_g_price': {'key': 'properties.payGPrice', 'type': 'float'}, - 'benefit_id': {'key': 'properties.benefitId', 'type': 'str'}, - 'benefit_name': {'key': 'properties.benefitName', 'type': 'str'}, - 'pricing_model': {'key': 'properties.pricingModel', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(LegacyUsageDetail, self).__init__(**kwargs) - self.kind = 'legacy' # type: str + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "billing_account_id": {"key": "properties.billingAccountId", "type": "str"}, + "billing_account_name": {"key": "properties.billingAccountName", "type": "str"}, + "billing_period_start_date": {"key": "properties.billingPeriodStartDate", "type": "iso-8601"}, + "billing_period_end_date": {"key": "properties.billingPeriodEndDate", "type": "iso-8601"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_name": {"key": "properties.billingProfileName", "type": "str"}, + "account_owner_id": {"key": "properties.accountOwnerId", "type": "str"}, + "account_name": {"key": "properties.accountName", "type": "str"}, + "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, + "subscription_name": {"key": "properties.subscriptionName", "type": "str"}, + "date": {"key": "properties.date", "type": "iso-8601"}, + "product": {"key": "properties.product", "type": "str"}, + "part_number": {"key": "properties.partNumber", "type": "str"}, + "meter_id": {"key": "properties.meterId", "type": "str"}, + "meter_details": {"key": "properties.meterDetails", "type": "MeterDetailsResponse"}, + "quantity": {"key": "properties.quantity", "type": "float"}, + "effective_price": {"key": "properties.effectivePrice", "type": "float"}, + "cost": {"key": "properties.cost", "type": "float"}, + "unit_price": {"key": "properties.unitPrice", "type": "float"}, + "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, + "resource_location": {"key": "properties.resourceLocation", "type": "str"}, + "consumed_service": {"key": "properties.consumedService", "type": "str"}, + "resource_id": {"key": "properties.resourceId", "type": "str"}, + "resource_name": {"key": "properties.resourceName", "type": "str"}, + "service_info1": {"key": "properties.serviceInfo1", "type": "str"}, + "service_info2": {"key": "properties.serviceInfo2", "type": "str"}, + "additional_info": {"key": "properties.additionalInfo", "type": "str"}, + "invoice_section": {"key": "properties.invoiceSection", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "resource_group": {"key": "properties.resourceGroup", "type": "str"}, + "reservation_id": {"key": "properties.reservationId", "type": "str"}, + "reservation_name": {"key": "properties.reservationName", "type": "str"}, + "product_order_id": {"key": "properties.productOrderId", "type": "str"}, + "product_order_name": {"key": "properties.productOrderName", "type": "str"}, + "offer_id": {"key": "properties.offerId", "type": "str"}, + "is_azure_credit_eligible": {"key": "properties.isAzureCreditEligible", "type": "bool"}, + "term": {"key": "properties.term", "type": "str"}, + "publisher_name": {"key": "properties.publisherName", "type": "str"}, + "publisher_type": {"key": "properties.publisherType", "type": "str"}, + "plan_name": {"key": "properties.planName", "type": "str"}, + "charge_type": {"key": "properties.chargeType", "type": "str"}, + "frequency": {"key": "properties.frequency", "type": "str"}, + "pay_g_price": {"key": "properties.payGPrice", "type": "float"}, + "benefit_id": {"key": "properties.benefitId", "type": "str"}, + "benefit_name": {"key": "properties.benefitName", "type": "str"}, + "pricing_model": {"key": "properties.pricingModel", "type": "str"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) + self.kind: str = "legacy" self.billing_account_id = None self.billing_account_name = None self.billing_period_start_date = None @@ -2609,7 +2480,7 @@ def __init__( self.pricing_model = None -class Lots(msrest.serialization.Model): +class Lots(_serialization.Model): """Result of listing lot summary. Variables are only populated by the server, and will be ignored when sending a request. @@ -2621,27 +2492,23 @@ class Lots(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[LotSummary]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[LotSummary]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Lots, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class LotSummary(ProxyResource): +class LotSummary(ProxyResource): # pylint: disable=too-many-instance-attributes """A lot summary resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2660,7 +2527,7 @@ class LotSummary(ProxyResource): :ivar closed_balance: The balance as of the last invoice. :vartype closed_balance: ~azure.mgmt.consumption.models.Amount :ivar source: The source of the lot. Known values are: "PurchasedCredit", "PromotionalCredit", - "ConsumptionCommitment". + and "ConsumptionCommitment". :vartype source: str or ~azure.mgmt.consumption.models.LotSource :ivar start_date: The date when the lot became effective. :vartype start_date: ~datetime.datetime @@ -2672,7 +2539,7 @@ class LotSummary(ProxyResource): :ivar purchased_date: The date when the lot was added. :vartype purchased_date: ~datetime.datetime :ivar status: The status of the lot. Known values are: "None", "Active", "Inactive", "Expired", - "Complete", "Canceled". + "Complete", and "Canceled". :vartype status: str or ~azure.mgmt.consumption.models.Status :ivar credit_currency: The currency of the lot. :vartype credit_currency: str @@ -2692,58 +2559,59 @@ class LotSummary(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'original_amount': {'readonly': True}, - 'closed_balance': {'readonly': True}, - 'source': {'readonly': True}, - 'start_date': {'readonly': True}, - 'expiration_date': {'readonly': True}, - 'po_number': {'readonly': True}, - 'purchased_date': {'readonly': True}, - 'status': {'readonly': True}, - 'credit_currency': {'readonly': True}, - 'billing_currency': {'readonly': True}, - 'original_amount_in_billing_currency': {'readonly': True}, - 'closed_balance_in_billing_currency': {'readonly': True}, - 'reseller': {'readonly': True}, - 'e_tag_properties_e_tag': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "original_amount": {"readonly": True}, + "closed_balance": {"readonly": True}, + "source": {"readonly": True}, + "start_date": {"readonly": True}, + "expiration_date": {"readonly": True}, + "po_number": {"readonly": True}, + "purchased_date": {"readonly": True}, + "status": {"readonly": True}, + "credit_currency": {"readonly": True}, + "billing_currency": {"readonly": True}, + "original_amount_in_billing_currency": {"readonly": True}, + "closed_balance_in_billing_currency": {"readonly": True}, + "reseller": {"readonly": True}, + "e_tag_properties_e_tag": {"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'}, - 'original_amount': {'key': 'properties.originalAmount', 'type': 'Amount'}, - 'closed_balance': {'key': 'properties.closedBalance', 'type': 'Amount'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'start_date': {'key': 'properties.startDate', 'type': 'iso-8601'}, - 'expiration_date': {'key': 'properties.expirationDate', 'type': 'iso-8601'}, - 'po_number': {'key': 'properties.poNumber', 'type': 'str'}, - 'purchased_date': {'key': 'properties.purchasedDate', 'type': 'iso-8601'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'credit_currency': {'key': 'properties.creditCurrency', 'type': 'str'}, - 'billing_currency': {'key': 'properties.billingCurrency', 'type': 'str'}, - 'original_amount_in_billing_currency': {'key': 'properties.originalAmountInBillingCurrency', 'type': 'AmountWithExchangeRate'}, - 'closed_balance_in_billing_currency': {'key': 'properties.closedBalanceInBillingCurrency', 'type': 'AmountWithExchangeRate'}, - 'reseller': {'key': 'properties.reseller', 'type': 'Reseller'}, - 'e_tag_properties_e_tag': {'key': 'properties.eTag', 'type': 'str'}, - } - - def __init__( - self, - *, - e_tag: Optional[str] = None, - **kwargs - ): + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "original_amount": {"key": "properties.originalAmount", "type": "Amount"}, + "closed_balance": {"key": "properties.closedBalance", "type": "Amount"}, + "source": {"key": "properties.source", "type": "str"}, + "start_date": {"key": "properties.startDate", "type": "iso-8601"}, + "expiration_date": {"key": "properties.expirationDate", "type": "iso-8601"}, + "po_number": {"key": "properties.poNumber", "type": "str"}, + "purchased_date": {"key": "properties.purchasedDate", "type": "iso-8601"}, + "status": {"key": "properties.status", "type": "str"}, + "credit_currency": {"key": "properties.creditCurrency", "type": "str"}, + "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, + "original_amount_in_billing_currency": { + "key": "properties.originalAmountInBillingCurrency", + "type": "AmountWithExchangeRate", + }, + "closed_balance_in_billing_currency": { + "key": "properties.closedBalanceInBillingCurrency", + "type": "AmountWithExchangeRate", + }, + "reseller": {"key": "properties.reseller", "type": "Reseller"}, + "e_tag_properties_e_tag": {"key": "properties.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(LotSummary, self).__init__(e_tag=e_tag, **kwargs) + super().__init__(e_tag=e_tag, **kwargs) self.original_amount = None self.closed_balance = None self.source = None @@ -2760,7 +2628,7 @@ def __init__( self.e_tag_properties_e_tag = None -class ManagementGroupAggregatedCostResult(Resource): +class ManagementGroupAggregatedCostResult(Resource): # pylint: disable=too-many-instance-attributes """A management group aggregated cost resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2773,7 +2641,7 @@ class ManagementGroupAggregatedCostResult(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar billing_period_id: The id of the billing period resource that the aggregated cost belongs to. @@ -2801,36 +2669,36 @@ class ManagementGroupAggregatedCostResult(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'billing_period_id': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'azure_charges': {'readonly': True}, - 'marketplace_charges': {'readonly': True}, - 'charges_billed_separately': {'readonly': True}, - 'currency': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "billing_period_id": {"readonly": True}, + "usage_start": {"readonly": True}, + "usage_end": {"readonly": True}, + "azure_charges": {"readonly": True}, + "marketplace_charges": {"readonly": True}, + "charges_billed_separately": {"readonly": True}, + "currency": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'billing_period_id': {'key': 'properties.billingPeriodId', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'iso-8601'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'iso-8601'}, - 'azure_charges': {'key': 'properties.azureCharges', 'type': 'float'}, - 'marketplace_charges': {'key': 'properties.marketplaceCharges', 'type': 'float'}, - 'charges_billed_separately': {'key': 'properties.chargesBilledSeparately', 'type': 'float'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'children': {'key': 'properties.children', 'type': '[ManagementGroupAggregatedCostResult]'}, - 'included_subscriptions': {'key': 'properties.includedSubscriptions', 'type': '[str]'}, - 'excluded_subscriptions': {'key': 'properties.excludedSubscriptions', 'type': '[str]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "billing_period_id": {"key": "properties.billingPeriodId", "type": "str"}, + "usage_start": {"key": "properties.usageStart", "type": "iso-8601"}, + "usage_end": {"key": "properties.usageEnd", "type": "iso-8601"}, + "azure_charges": {"key": "properties.azureCharges", "type": "float"}, + "marketplace_charges": {"key": "properties.marketplaceCharges", "type": "float"}, + "charges_billed_separately": {"key": "properties.chargesBilledSeparately", "type": "float"}, + "currency": {"key": "properties.currency", "type": "str"}, + "children": {"key": "properties.children", "type": "[ManagementGroupAggregatedCostResult]"}, + "included_subscriptions": {"key": "properties.includedSubscriptions", "type": "[str]"}, + "excluded_subscriptions": {"key": "properties.excludedSubscriptions", "type": "[str]"}, } def __init__( @@ -2851,7 +2719,7 @@ def __init__( aggregated cost. :paramtype excluded_subscriptions: list[str] """ - super(ManagementGroupAggregatedCostResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.billing_period_id = None self.usage_start = None self.usage_end = None @@ -2864,7 +2732,7 @@ def __init__( self.excluded_subscriptions = excluded_subscriptions -class Marketplace(Resource): +class Marketplace(Resource): # pylint: disable=too-many-instance-attributes """A marketplace resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2877,7 +2745,7 @@ class Marketplace(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar billing_period_id: The id of the billing period resource that the usage belongs to. :vartype billing_period_id: str @@ -2936,80 +2804,76 @@ class Marketplace(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'billing_period_id': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'resource_rate': {'readonly': True}, - 'offer_name': {'readonly': True}, - 'resource_group': {'readonly': True}, - 'additional_info': {'readonly': True}, - 'order_number': {'readonly': True}, - 'instance_name': {'readonly': True}, - 'instance_id': {'readonly': True}, - 'currency': {'readonly': True}, - 'consumed_quantity': {'readonly': True}, - 'unit_of_measure': {'readonly': True}, - 'pretax_cost': {'readonly': True}, - 'is_estimated': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'subscription_guid': {'readonly': True}, - 'subscription_name': {'readonly': True}, - 'account_name': {'readonly': True}, - 'department_name': {'readonly': True}, - 'consumed_service': {'readonly': True}, - 'cost_center': {'readonly': True}, - 'additional_properties': {'readonly': True}, - 'publisher_name': {'readonly': True}, - 'plan_name': {'readonly': True}, - 'is_recurring_charge': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "billing_period_id": {"readonly": True}, + "usage_start": {"readonly": True}, + "usage_end": {"readonly": True}, + "resource_rate": {"readonly": True}, + "offer_name": {"readonly": True}, + "resource_group": {"readonly": True}, + "additional_info": {"readonly": True}, + "order_number": {"readonly": True}, + "instance_name": {"readonly": True}, + "instance_id": {"readonly": True}, + "currency": {"readonly": True}, + "consumed_quantity": {"readonly": True}, + "unit_of_measure": {"readonly": True}, + "pretax_cost": {"readonly": True}, + "is_estimated": {"readonly": True}, + "meter_id": {"readonly": True}, + "subscription_guid": {"readonly": True}, + "subscription_name": {"readonly": True}, + "account_name": {"readonly": True}, + "department_name": {"readonly": True}, + "consumed_service": {"readonly": True}, + "cost_center": {"readonly": True}, + "additional_properties": {"readonly": True}, + "publisher_name": {"readonly": True}, + "plan_name": {"readonly": True}, + "is_recurring_charge": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'billing_period_id': {'key': 'properties.billingPeriodId', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'iso-8601'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'iso-8601'}, - 'resource_rate': {'key': 'properties.resourceRate', 'type': 'float'}, - 'offer_name': {'key': 'properties.offerName', 'type': 'str'}, - 'resource_group': {'key': 'properties.resourceGroup', 'type': 'str'}, - 'additional_info': {'key': 'properties.additionalInfo', 'type': 'str'}, - 'order_number': {'key': 'properties.orderNumber', 'type': 'str'}, - 'instance_name': {'key': 'properties.instanceName', 'type': 'str'}, - 'instance_id': {'key': 'properties.instanceId', 'type': 'str'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'consumed_quantity': {'key': 'properties.consumedQuantity', 'type': 'float'}, - 'unit_of_measure': {'key': 'properties.unitOfMeasure', 'type': 'str'}, - 'pretax_cost': {'key': 'properties.pretaxCost', 'type': 'float'}, - 'is_estimated': {'key': 'properties.isEstimated', 'type': 'bool'}, - 'meter_id': {'key': 'properties.meterId', 'type': 'str'}, - 'subscription_guid': {'key': 'properties.subscriptionGuid', 'type': 'str'}, - 'subscription_name': {'key': 'properties.subscriptionName', 'type': 'str'}, - 'account_name': {'key': 'properties.accountName', 'type': 'str'}, - 'department_name': {'key': 'properties.departmentName', 'type': 'str'}, - 'consumed_service': {'key': 'properties.consumedService', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'additional_properties': {'key': 'properties.additionalProperties', 'type': 'str'}, - 'publisher_name': {'key': 'properties.publisherName', 'type': 'str'}, - 'plan_name': {'key': 'properties.planName', 'type': 'str'}, - 'is_recurring_charge': {'key': 'properties.isRecurringCharge', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(Marketplace, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "billing_period_id": {"key": "properties.billingPeriodId", "type": "str"}, + "usage_start": {"key": "properties.usageStart", "type": "iso-8601"}, + "usage_end": {"key": "properties.usageEnd", "type": "iso-8601"}, + "resource_rate": {"key": "properties.resourceRate", "type": "float"}, + "offer_name": {"key": "properties.offerName", "type": "str"}, + "resource_group": {"key": "properties.resourceGroup", "type": "str"}, + "additional_info": {"key": "properties.additionalInfo", "type": "str"}, + "order_number": {"key": "properties.orderNumber", "type": "str"}, + "instance_name": {"key": "properties.instanceName", "type": "str"}, + "instance_id": {"key": "properties.instanceId", "type": "str"}, + "currency": {"key": "properties.currency", "type": "str"}, + "consumed_quantity": {"key": "properties.consumedQuantity", "type": "float"}, + "unit_of_measure": {"key": "properties.unitOfMeasure", "type": "str"}, + "pretax_cost": {"key": "properties.pretaxCost", "type": "float"}, + "is_estimated": {"key": "properties.isEstimated", "type": "bool"}, + "meter_id": {"key": "properties.meterId", "type": "str"}, + "subscription_guid": {"key": "properties.subscriptionGuid", "type": "str"}, + "subscription_name": {"key": "properties.subscriptionName", "type": "str"}, + "account_name": {"key": "properties.accountName", "type": "str"}, + "department_name": {"key": "properties.departmentName", "type": "str"}, + "consumed_service": {"key": "properties.consumedService", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "additional_properties": {"key": "properties.additionalProperties", "type": "str"}, + "publisher_name": {"key": "properties.publisherName", "type": "str"}, + "plan_name": {"key": "properties.planName", "type": "str"}, + "is_recurring_charge": {"key": "properties.isRecurringCharge", "type": "bool"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) self.billing_period_id = None self.usage_start = None self.usage_end = None @@ -3038,7 +2902,7 @@ def __init__( self.is_recurring_charge = None -class MarketplacesListResult(msrest.serialization.Model): +class MarketplacesListResult(_serialization.Model): """Result of listing marketplaces. It contains a list of available marketplaces in reverse chronological order by billing period. Variables are only populated by the server, and will be ignored when sending a request. @@ -3050,27 +2914,23 @@ class MarketplacesListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Marketplace]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Marketplace]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(MarketplacesListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class MeterDetails(msrest.serialization.Model): +class MeterDetails(_serialization.Model): """The properties of the meter detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -3099,36 +2959,32 @@ class MeterDetails(msrest.serialization.Model): """ _validation = { - 'meter_name': {'readonly': True}, - 'meter_category': {'readonly': True}, - 'meter_sub_category': {'readonly': True}, - 'unit': {'readonly': True}, - 'meter_location': {'readonly': True}, - 'total_included_quantity': {'readonly': True}, - 'pretax_standard_rate': {'readonly': True}, - 'service_name': {'readonly': True}, - 'service_tier': {'readonly': True}, + "meter_name": {"readonly": True}, + "meter_category": {"readonly": True}, + "meter_sub_category": {"readonly": True}, + "unit": {"readonly": True}, + "meter_location": {"readonly": True}, + "total_included_quantity": {"readonly": True}, + "pretax_standard_rate": {"readonly": True}, + "service_name": {"readonly": True}, + "service_tier": {"readonly": True}, } _attribute_map = { - 'meter_name': {'key': 'meterName', 'type': 'str'}, - 'meter_category': {'key': 'meterCategory', 'type': 'str'}, - 'meter_sub_category': {'key': 'meterSubCategory', 'type': 'str'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'meter_location': {'key': 'meterLocation', 'type': 'str'}, - 'total_included_quantity': {'key': 'totalIncludedQuantity', 'type': 'float'}, - 'pretax_standard_rate': {'key': 'pretaxStandardRate', 'type': 'float'}, - 'service_name': {'key': 'serviceName', 'type': 'str'}, - 'service_tier': {'key': 'serviceTier', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(MeterDetails, self).__init__(**kwargs) + "meter_name": {"key": "meterName", "type": "str"}, + "meter_category": {"key": "meterCategory", "type": "str"}, + "meter_sub_category": {"key": "meterSubCategory", "type": "str"}, + "unit": {"key": "unit", "type": "str"}, + "meter_location": {"key": "meterLocation", "type": "str"}, + "total_included_quantity": {"key": "totalIncludedQuantity", "type": "float"}, + "pretax_standard_rate": {"key": "pretaxStandardRate", "type": "float"}, + "service_name": {"key": "serviceName", "type": "str"}, + "service_tier": {"key": "serviceTier", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.meter_name = None self.meter_category = None self.meter_sub_category = None @@ -3140,7 +2996,7 @@ def __init__( self.service_tier = None -class MeterDetailsResponse(msrest.serialization.Model): +class MeterDetailsResponse(_serialization.Model): """The properties of the meter detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -3161,28 +3017,24 @@ class MeterDetailsResponse(msrest.serialization.Model): """ _validation = { - 'meter_name': {'readonly': True}, - 'meter_category': {'readonly': True}, - 'meter_sub_category': {'readonly': True}, - 'unit_of_measure': {'readonly': True}, - 'service_family': {'readonly': True}, + "meter_name": {"readonly": True}, + "meter_category": {"readonly": True}, + "meter_sub_category": {"readonly": True}, + "unit_of_measure": {"readonly": True}, + "service_family": {"readonly": True}, } _attribute_map = { - 'meter_name': {'key': 'meterName', 'type': 'str'}, - 'meter_category': {'key': 'meterCategory', 'type': 'str'}, - 'meter_sub_category': {'key': 'meterSubCategory', 'type': 'str'}, - 'unit_of_measure': {'key': 'unitOfMeasure', 'type': 'str'}, - 'service_family': {'key': 'serviceFamily', 'type': 'str'}, + "meter_name": {"key": "meterName", "type": "str"}, + "meter_category": {"key": "meterCategory", "type": "str"}, + "meter_sub_category": {"key": "meterSubCategory", "type": "str"}, + "unit_of_measure": {"key": "unitOfMeasure", "type": "str"}, + "service_family": {"key": "serviceFamily", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(MeterDetailsResponse, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.meter_name = None self.meter_category = None self.meter_sub_category = None @@ -3190,24 +3042,25 @@ def __init__( self.service_family = None -class ModernChargeSummary(ChargeSummary): +class ModernChargeSummary(ChargeSummary): # pylint: disable=too-many-instance-attributes """Modern charge summary. 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 id: Resource Id. + :ivar id: The full qualified ARM ID of an event. :vartype id: str - :ivar name: Resource name. + :ivar name: The ID that uniquely identifies an event. :vartype name: str :ivar type: Resource type. :vartype type: 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 kind: Required. Specifies the kind of charge summary.Constant filled by server. Known - values are: "legacy", "modern". + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar kind: Specifies the kind of charge summary. Required. Known values are: "legacy" and + "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ChargeSummaryKind :ivar billing_period_id: The id of the billing period resource that the charge belongs to. :vartype billing_period_id: str @@ -3234,55 +3087,49 @@ class ModernChargeSummary(ChargeSummary): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'kind': {'required': True}, - 'billing_period_id': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'azure_charges': {'readonly': True}, - 'charges_billed_separately': {'readonly': True}, - 'marketplace_charges': {'readonly': True}, - 'billing_account_id': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'customer_id': {'readonly': True}, - 'is_invoiced': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, + "billing_period_id": {"readonly": True}, + "usage_start": {"readonly": True}, + "usage_end": {"readonly": True}, + "azure_charges": {"readonly": True}, + "charges_billed_separately": {"readonly": True}, + "marketplace_charges": {"readonly": True}, + "billing_account_id": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "invoice_section_id": {"readonly": True}, + "customer_id": {"readonly": True}, + "is_invoiced": {"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'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'billing_period_id': {'key': 'properties.billingPeriodId', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'str'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'str'}, - 'azure_charges': {'key': 'properties.azureCharges', 'type': 'Amount'}, - 'charges_billed_separately': {'key': 'properties.chargesBilledSeparately', 'type': 'Amount'}, - 'marketplace_charges': {'key': 'properties.marketplaceCharges', 'type': 'Amount'}, - 'billing_account_id': {'key': 'properties.billingAccountId', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'customer_id': {'key': 'properties.customerId', 'type': 'str'}, - 'is_invoiced': {'key': 'properties.isInvoiced', 'type': 'bool'}, - } - - 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(ModernChargeSummary, self).__init__(e_tag=e_tag, **kwargs) - self.kind = 'modern' # type: str + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "billing_period_id": {"key": "properties.billingPeriodId", "type": "str"}, + "usage_start": {"key": "properties.usageStart", "type": "str"}, + "usage_end": {"key": "properties.usageEnd", "type": "str"}, + "azure_charges": {"key": "properties.azureCharges", "type": "Amount"}, + "charges_billed_separately": {"key": "properties.chargesBilledSeparately", "type": "Amount"}, + "marketplace_charges": {"key": "properties.marketplaceCharges", "type": "Amount"}, + "billing_account_id": {"key": "properties.billingAccountId", "type": "str"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, + "customer_id": {"key": "properties.customerId", "type": "str"}, + "is_invoiced": {"key": "properties.isInvoiced", "type": "bool"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.kind: str = "modern" self.billing_period_id = None self.usage_start = None self.usage_end = None @@ -3296,7 +3143,7 @@ def __init__( self.is_invoiced = None -class ModernReservationRecommendation(ReservationRecommendation): +class ModernReservationRecommendation(ReservationRecommendation): # pylint: disable=too-many-instance-attributes """Modern reservation recommendation. Variables are only populated by the server, and will be ignored when sending a request. @@ -3315,10 +3162,10 @@ class ModernReservationRecommendation(ReservationRecommendation): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar kind: Required. Specifies the kind of reservation recommendation.Constant filled by - server. Known values are: "legacy", "modern". + :ivar kind: Specifies the kind of reservation recommendation. Required. Known values are: + "legacy" and "modern". :vartype kind: str or ~azure.mgmt.consumption.models.ReservationRecommendationKind :ivar location_properties_location: Resource Location. :vartype location_properties_location: str @@ -3340,13 +3187,15 @@ class ModernReservationRecommendation(ReservationRecommendation): :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount :ivar recommended_quantity: Recommended quality for reserved instances. :vartype recommended_quantity: float + :ivar resource_type: Resource type. + :vartype resource_type: str :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. :vartype total_cost_with_reserved_instances: ~azure.mgmt.consumption.models.Amount :ivar net_savings: Total estimated savings with reserved instances. :vartype net_savings: ~azure.mgmt.consumption.models.Amount :ivar first_usage_date: The usage date for looking back. :vartype first_usage_date: ~datetime.datetime - :ivar scope: Shared or single recommendation. + :ivar scope: Shared or single recommendation. Required. :vartype scope: str :ivar sku_properties: List of sku properties. :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] @@ -3355,68 +3204,182 @@ class ModernReservationRecommendation(ReservationRecommendation): """ _validation = { - 'location': {'readonly': True}, - 'sku': {'readonly': True}, - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'kind': {'required': True}, - 'location_properties_location': {'readonly': True}, - 'look_back_period': {'readonly': True}, - 'instance_flexibility_ratio': {'readonly': True}, - 'instance_flexibility_group': {'readonly': True}, - 'normalized_size': {'readonly': True}, - 'recommended_quantity_normalized': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'term': {'readonly': True}, - 'cost_with_no_reserved_instances': {'readonly': True}, - 'recommended_quantity': {'readonly': True}, - 'total_cost_with_reserved_instances': {'readonly': True}, - 'net_savings': {'readonly': True}, - 'first_usage_date': {'readonly': True}, - 'scope': {'readonly': True}, - 'sku_properties': {'readonly': True}, - 'sku_name': {'readonly': True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, + "location_properties_location": {"readonly": True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "resource_type": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, + "sku_name": {"readonly": True}, } _attribute_map = { - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'location_properties_location': {'key': 'properties.location', 'type': 'str'}, - 'look_back_period': {'key': 'properties.lookBackPeriod', 'type': 'int'}, - 'instance_flexibility_ratio': {'key': 'properties.instanceFlexibilityRatio', 'type': 'float'}, - 'instance_flexibility_group': {'key': 'properties.instanceFlexibilityGroup', 'type': 'str'}, - 'normalized_size': {'key': 'properties.normalizedSize', 'type': 'str'}, - 'recommended_quantity_normalized': {'key': 'properties.recommendedQuantityNormalized', 'type': 'float'}, - 'meter_id': {'key': 'properties.meterId', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'cost_with_no_reserved_instances': {'key': 'properties.costWithNoReservedInstances', 'type': 'Amount'}, - 'recommended_quantity': {'key': 'properties.recommendedQuantity', 'type': 'float'}, - 'total_cost_with_reserved_instances': {'key': 'properties.totalCostWithReservedInstances', 'type': 'Amount'}, - 'net_savings': {'key': 'properties.netSavings', 'type': 'Amount'}, - 'first_usage_date': {'key': 'properties.firstUsageDate', 'type': 'iso-8601'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'sku_properties': {'key': 'properties.skuProperties', 'type': '[SkuProperty]'}, - 'sku_name': {'key': 'properties.skuName', 'type': 'str'}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "location_properties_location": {"key": "properties.location", "type": "str"}, + "look_back_period": {"key": "properties.lookBackPeriod", "type": "int"}, + "instance_flexibility_ratio": {"key": "properties.instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "properties.instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "properties.normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "properties.recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "properties.meterId", "type": "str"}, + "term": {"key": "properties.term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "properties.costWithNoReservedInstances", "type": "Amount"}, + "recommended_quantity": {"key": "properties.recommendedQuantity", "type": "float"}, + "resource_type": {"key": "properties.resourceType", "type": "str"}, + "total_cost_with_reserved_instances": {"key": "properties.totalCostWithReservedInstances", "type": "Amount"}, + "net_savings": {"key": "properties.netSavings", "type": "Amount"}, + "first_usage_date": {"key": "properties.firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "properties.scope", "type": "str"}, + "sku_properties": {"key": "properties.skuProperties", "type": "[SkuProperty]"}, + "sku_name": {"key": "properties.skuName", "type": "str"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) + self.kind: str = "modern" + self.location_properties_location = None + self.look_back_period = None + self.instance_flexibility_ratio = None + self.instance_flexibility_group = None + self.normalized_size = None + self.recommended_quantity_normalized = None + self.meter_id = None + self.term = None + self.cost_with_no_reserved_instances = None + self.recommended_quantity = None + self.resource_type = None + self.total_cost_with_reserved_instances = None + self.net_savings = None + self.first_usage_date = None + self.scope: str = "modern" + self.sku_properties = None + self.sku_name = None + + +class ModernReservationRecommendationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The properties of the reservation recommendation. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ModernSharedScopeReservationRecommendationProperties, + ModernSingleScopeReservationRecommendationProperties + + 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 location: Resource Location. + :vartype location: str + :ivar look_back_period: The number of days of usage to look back for recommendation. + :vartype look_back_period: int + :ivar instance_flexibility_ratio: The instance Flexibility Ratio. + :vartype instance_flexibility_ratio: float + :ivar instance_flexibility_group: The instance Flexibility Group. + :vartype instance_flexibility_group: str + :ivar normalized_size: The normalized Size. + :vartype normalized_size: str + :ivar recommended_quantity_normalized: The recommended Quantity Normalized. + :vartype recommended_quantity_normalized: float + :ivar meter_id: The meter id (GUID). + :vartype meter_id: str + :ivar term: RI recommendations in one or three year terms. + :vartype term: str + :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. + :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount + :ivar recommended_quantity: Recommended quality for reserved instances. + :vartype recommended_quantity: float + :ivar resource_type: Resource type. + :vartype resource_type: str + :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. + :vartype total_cost_with_reserved_instances: ~azure.mgmt.consumption.models.Amount + :ivar net_savings: Total estimated savings with reserved instances. + :vartype net_savings: ~azure.mgmt.consumption.models.Amount + :ivar first_usage_date: The usage date for looking back. + :vartype first_usage_date: ~datetime.datetime + :ivar scope: Shared or single recommendation. Required. + :vartype scope: str + :ivar sku_properties: List of sku properties. + :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar sku_name: This is the ARM Sku name. + :vartype sku_name: str + """ + + _validation = { + "location": {"readonly": True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "resource_type": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, + "sku_name": {"readonly": True}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ModernReservationRecommendation, self).__init__(**kwargs) - self.kind = 'modern' # type: str - self.location_properties_location = None + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "look_back_period": {"key": "lookBackPeriod", "type": "int"}, + "instance_flexibility_ratio": {"key": "instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "meterId", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "costWithNoReservedInstances", "type": "Amount"}, + "recommended_quantity": {"key": "recommendedQuantity", "type": "float"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "total_cost_with_reserved_instances": {"key": "totalCostWithReservedInstances", "type": "Amount"}, + "net_savings": {"key": "netSavings", "type": "Amount"}, + "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "scope", "type": "str"}, + "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "sku_name": {"key": "skuName", "type": "str"}, + } + + _subtype_map = { + "scope": { + "Shared": "ModernSharedScopeReservationRecommendationProperties", + "Single": "ModernSingleScopeReservationRecommendationProperties", + } + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.location = None self.look_back_period = None self.instance_flexibility_ratio = None self.instance_flexibility_group = None @@ -3426,15 +3389,16 @@ def __init__( self.term = None self.cost_with_no_reserved_instances = None self.recommended_quantity = None + self.resource_type = None self.total_cost_with_reserved_instances = None self.net_savings = None self.first_usage_date = None - self.scope = None + self.scope: Optional[str] = None self.sku_properties = None self.sku_name = None -class ModernReservationTransaction(ReservationTransactionResource): +class ModernReservationTransaction(ReservationTransactionResource): # pylint: disable=too-many-instance-attributes """Modern Reservation transaction resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -3445,7 +3409,7 @@ class ModernReservationTransaction(ReservationTransactionResource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: list[str] :ivar amount: The charge of the transaction. :vartype amount: float @@ -3464,7 +3428,7 @@ class ModernReservationTransaction(ReservationTransactionResource): :vartype description: str :ivar event_date: The date of the transaction. :vartype event_date: ~datetime.datetime - :ivar event_type: The type of the transaction (Purchase, Cancel, etc.). + :ivar event_type: The type of the transaction (Purchase, Cancel or Refund). :vartype event_type: str :ivar invoice: Invoice Number. :vartype invoice: str @@ -3494,66 +3458,62 @@ class ModernReservationTransaction(ReservationTransactionResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'amount': {'readonly': True}, - 'arm_sku_name': {'readonly': True}, - 'billing_frequency': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_name': {'readonly': True}, - 'currency': {'readonly': True}, - 'description': {'readonly': True}, - 'event_date': {'readonly': True}, - 'event_type': {'readonly': True}, - 'invoice': {'readonly': True}, - 'invoice_id': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_name': {'readonly': True}, - 'purchasing_subscription_guid': {'readonly': True}, - 'purchasing_subscription_name': {'readonly': True}, - 'quantity': {'readonly': True}, - 'region': {'readonly': True}, - 'reservation_order_id': {'readonly': True}, - 'reservation_order_name': {'readonly': True}, - 'term': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "tags": {"readonly": True}, + "amount": {"readonly": True}, + "arm_sku_name": {"readonly": True}, + "billing_frequency": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_name": {"readonly": True}, + "currency": {"readonly": True}, + "description": {"readonly": True}, + "event_date": {"readonly": True}, + "event_type": {"readonly": True}, + "invoice": {"readonly": True}, + "invoice_id": {"readonly": True}, + "invoice_section_id": {"readonly": True}, + "invoice_section_name": {"readonly": True}, + "purchasing_subscription_guid": {"readonly": True}, + "purchasing_subscription_name": {"readonly": True}, + "quantity": {"readonly": True}, + "region": {"readonly": True}, + "reservation_order_id": {"readonly": True}, + "reservation_order_name": {"readonly": True}, + "term": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '[str]'}, - 'amount': {'key': 'properties.amount', 'type': 'float'}, - 'arm_sku_name': {'key': 'properties.armSkuName', 'type': 'str'}, - 'billing_frequency': {'key': 'properties.billingFrequency', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_name': {'key': 'properties.billingProfileName', 'type': 'str'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'event_date': {'key': 'properties.eventDate', 'type': 'iso-8601'}, - 'event_type': {'key': 'properties.eventType', 'type': 'str'}, - 'invoice': {'key': 'properties.invoice', 'type': 'str'}, - 'invoice_id': {'key': 'properties.invoiceId', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_name': {'key': 'properties.invoiceSectionName', 'type': 'str'}, - 'purchasing_subscription_guid': {'key': 'properties.purchasingSubscriptionGuid', 'type': 'str'}, - 'purchasing_subscription_name': {'key': 'properties.purchasingSubscriptionName', 'type': 'str'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'region': {'key': 'properties.region', 'type': 'str'}, - 'reservation_order_id': {'key': 'properties.reservationOrderId', 'type': 'str'}, - 'reservation_order_name': {'key': 'properties.reservationOrderName', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(ModernReservationTransaction, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "[str]"}, + "amount": {"key": "properties.amount", "type": "float"}, + "arm_sku_name": {"key": "properties.armSkuName", "type": "str"}, + "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_name": {"key": "properties.billingProfileName", "type": "str"}, + "currency": {"key": "properties.currency", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "event_date": {"key": "properties.eventDate", "type": "iso-8601"}, + "event_type": {"key": "properties.eventType", "type": "str"}, + "invoice": {"key": "properties.invoice", "type": "str"}, + "invoice_id": {"key": "properties.invoiceId", "type": "str"}, + "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, + "invoice_section_name": {"key": "properties.invoiceSectionName", "type": "str"}, + "purchasing_subscription_guid": {"key": "properties.purchasingSubscriptionGuid", "type": "str"}, + "purchasing_subscription_name": {"key": "properties.purchasingSubscriptionName", "type": "str"}, + "quantity": {"key": "properties.quantity", "type": "float"}, + "region": {"key": "properties.region", "type": "str"}, + "reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"}, + "reservation_order_name": {"key": "properties.reservationOrderName", "type": "str"}, + "term": {"key": "properties.term", "type": "str"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) self.amount = None self.arm_sku_name = None self.billing_frequency = None @@ -3576,7 +3536,7 @@ def __init__( self.term = None -class ModernReservationTransactionsListResult(msrest.serialization.Model): +class ModernReservationTransactionsListResult(_serialization.Model): """Result of listing reservation recommendations. Variables are only populated by the server, and will be ignored when sending a request. @@ -3588,27 +3548,210 @@ class ModernReservationTransactionsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ModernReservationTransaction]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ModernReservationTransaction]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ModernReservationTransactionsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class ModernUsageDetail(UsageDetail): +class ModernSharedScopeReservationRecommendationProperties( + ModernReservationRecommendationProperties +): # pylint: disable=too-many-instance-attributes + """The properties of the modern reservation recommendation for shared scope. + + 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 location: Resource Location. + :vartype location: str + :ivar look_back_period: The number of days of usage to look back for recommendation. + :vartype look_back_period: int + :ivar instance_flexibility_ratio: The instance Flexibility Ratio. + :vartype instance_flexibility_ratio: float + :ivar instance_flexibility_group: The instance Flexibility Group. + :vartype instance_flexibility_group: str + :ivar normalized_size: The normalized Size. + :vartype normalized_size: str + :ivar recommended_quantity_normalized: The recommended Quantity Normalized. + :vartype recommended_quantity_normalized: float + :ivar meter_id: The meter id (GUID). + :vartype meter_id: str + :ivar term: RI recommendations in one or three year terms. + :vartype term: str + :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. + :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount + :ivar recommended_quantity: Recommended quality for reserved instances. + :vartype recommended_quantity: float + :ivar resource_type: Resource type. + :vartype resource_type: str + :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. + :vartype total_cost_with_reserved_instances: ~azure.mgmt.consumption.models.Amount + :ivar net_savings: Total estimated savings with reserved instances. + :vartype net_savings: ~azure.mgmt.consumption.models.Amount + :ivar first_usage_date: The usage date for looking back. + :vartype first_usage_date: ~datetime.datetime + :ivar scope: Shared or single recommendation. Required. + :vartype scope: str + :ivar sku_properties: List of sku properties. + :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar sku_name: This is the ARM Sku name. + :vartype sku_name: str + """ + + _validation = { + "location": {"readonly": True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "resource_type": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, + "sku_name": {"readonly": True}, + } + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "look_back_period": {"key": "lookBackPeriod", "type": "int"}, + "instance_flexibility_ratio": {"key": "instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "meterId", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "costWithNoReservedInstances", "type": "Amount"}, + "recommended_quantity": {"key": "recommendedQuantity", "type": "float"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "total_cost_with_reserved_instances": {"key": "totalCostWithReservedInstances", "type": "Amount"}, + "net_savings": {"key": "netSavings", "type": "Amount"}, + "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "scope", "type": "str"}, + "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "sku_name": {"key": "skuName", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.scope: str = "Shared" + + +class ModernSingleScopeReservationRecommendationProperties( + ModernReservationRecommendationProperties +): # pylint: disable=too-many-instance-attributes + """The properties of the modern reservation recommendation for single scope. + + 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 location: Resource Location. + :vartype location: str + :ivar look_back_period: The number of days of usage to look back for recommendation. + :vartype look_back_period: int + :ivar instance_flexibility_ratio: The instance Flexibility Ratio. + :vartype instance_flexibility_ratio: float + :ivar instance_flexibility_group: The instance Flexibility Group. + :vartype instance_flexibility_group: str + :ivar normalized_size: The normalized Size. + :vartype normalized_size: str + :ivar recommended_quantity_normalized: The recommended Quantity Normalized. + :vartype recommended_quantity_normalized: float + :ivar meter_id: The meter id (GUID). + :vartype meter_id: str + :ivar term: RI recommendations in one or three year terms. + :vartype term: str + :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. + :vartype cost_with_no_reserved_instances: ~azure.mgmt.consumption.models.Amount + :ivar recommended_quantity: Recommended quality for reserved instances. + :vartype recommended_quantity: float + :ivar resource_type: Resource type. + :vartype resource_type: str + :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. + :vartype total_cost_with_reserved_instances: ~azure.mgmt.consumption.models.Amount + :ivar net_savings: Total estimated savings with reserved instances. + :vartype net_savings: ~azure.mgmt.consumption.models.Amount + :ivar first_usage_date: The usage date for looking back. + :vartype first_usage_date: ~datetime.datetime + :ivar scope: Shared or single recommendation. Required. + :vartype scope: str + :ivar sku_properties: List of sku properties. + :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar sku_name: This is the ARM Sku name. + :vartype sku_name: str + :ivar subscription_id: Subscription ID associated with single scoped recommendation. + :vartype subscription_id: str + """ + + _validation = { + "location": {"readonly": True}, + "look_back_period": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "normalized_size": {"readonly": True}, + "recommended_quantity_normalized": {"readonly": True}, + "meter_id": {"readonly": True}, + "term": {"readonly": True}, + "cost_with_no_reserved_instances": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "resource_type": {"readonly": True}, + "total_cost_with_reserved_instances": {"readonly": True}, + "net_savings": {"readonly": True}, + "first_usage_date": {"readonly": True}, + "scope": {"required": True}, + "sku_properties": {"readonly": True}, + "sku_name": {"readonly": True}, + "subscription_id": {"readonly": True}, + } + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "look_back_period": {"key": "lookBackPeriod", "type": "int"}, + "instance_flexibility_ratio": {"key": "instanceFlexibilityRatio", "type": "float"}, + "instance_flexibility_group": {"key": "instanceFlexibilityGroup", "type": "str"}, + "normalized_size": {"key": "normalizedSize", "type": "str"}, + "recommended_quantity_normalized": {"key": "recommendedQuantityNormalized", "type": "float"}, + "meter_id": {"key": "meterId", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "cost_with_no_reserved_instances": {"key": "costWithNoReservedInstances", "type": "Amount"}, + "recommended_quantity": {"key": "recommendedQuantity", "type": "float"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "total_cost_with_reserved_instances": {"key": "totalCostWithReservedInstances", "type": "Amount"}, + "net_savings": {"key": "netSavings", "type": "Amount"}, + "first_usage_date": {"key": "firstUsageDate", "type": "iso-8601"}, + "scope": {"key": "scope", "type": "str"}, + "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, + "sku_name": {"key": "skuName", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.scope: str = "Single" + self.subscription_id = None + + +class ModernUsageDetail(UsageDetail): # pylint: disable=too-many-instance-attributes """Modern usage detail. Variables are only populated by the server, and will be ignored when sending a request. @@ -3623,17 +3766,17 @@ class ModernUsageDetail(UsageDetail): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar kind: Required. Specifies the kind of usage details.Constant filled by server. Known - values are: "legacy", "modern". + :ivar kind: Specifies the kind of usage details. Required. Known values are: "legacy" and + "modern". :vartype kind: str or ~azure.mgmt.consumption.models.UsageDetailsKind :ivar billing_account_id: Billing Account identifier. :vartype billing_account_id: str :ivar effective_price: Effective Price that's charged for the usage. :vartype effective_price: float :ivar pricing_model: Identifier that indicates how the meter is priced. Known values are: "On - Demand", "Reservation", "Spot". + Demand", "Reservation", and "Spot". :vartype pricing_model: str or ~azure.mgmt.consumption.models.PricingModelType :ivar billing_account_name: Name of the Billing Account. :vartype billing_account_name: str @@ -3822,175 +3965,171 @@ class ModernUsageDetail(UsageDetail): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'kind': {'required': True}, - 'billing_account_id': {'readonly': True}, - 'effective_price': {'readonly': True}, - 'pricing_model': {'readonly': True}, - 'billing_account_name': {'readonly': True}, - 'billing_period_start_date': {'readonly': True}, - 'billing_period_end_date': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_name': {'readonly': True}, - 'subscription_guid': {'readonly': True}, - 'subscription_name': {'readonly': True}, - 'date': {'readonly': True}, - 'product': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'meter_name': {'readonly': True}, - 'meter_region': {'readonly': True}, - 'meter_category': {'readonly': True}, - 'meter_sub_category': {'readonly': True}, - 'service_family': {'readonly': True}, - 'quantity': {'readonly': True}, - 'unit_of_measure': {'readonly': True}, - 'instance_name': {'readonly': True}, - 'cost_in_usd': {'readonly': True}, - 'unit_price': {'readonly': True}, - 'billing_currency_code': {'readonly': True}, - 'resource_location': {'readonly': True}, - 'consumed_service': {'readonly': True}, - 'service_info1': {'readonly': True}, - 'service_info2': {'readonly': True}, - 'additional_info': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_name': {'readonly': True}, - 'cost_center': {'readonly': True}, - 'resource_group': {'readonly': True}, - 'reservation_id': {'readonly': True}, - 'reservation_name': {'readonly': True}, - 'product_order_id': {'readonly': True}, - 'product_order_name': {'readonly': True}, - 'is_azure_credit_eligible': {'readonly': True}, - 'term': {'readonly': True}, - 'publisher_name': {'readonly': True}, - 'publisher_type': {'readonly': True}, - 'charge_type': {'readonly': True}, - 'frequency': {'readonly': True}, - 'cost_in_billing_currency': {'readonly': True}, - 'cost_in_pricing_currency': {'readonly': True}, - 'exchange_rate': {'readonly': True}, - 'exchange_rate_date': {'readonly': True}, - 'invoice_id': {'readonly': True}, - 'previous_invoice_id': {'readonly': True}, - 'pricing_currency_code': {'readonly': True}, - 'product_identifier': {'readonly': True}, - 'resource_location_normalized': {'readonly': True}, - 'service_period_start_date': {'readonly': True}, - 'service_period_end_date': {'readonly': True}, - 'customer_tenant_id': {'readonly': True}, - 'customer_name': {'readonly': True}, - 'partner_tenant_id': {'readonly': True}, - 'partner_name': {'readonly': True}, - 'reseller_mpn_id': {'readonly': True}, - 'reseller_name': {'readonly': True}, - 'publisher_id': {'readonly': True}, - 'market_price': {'readonly': True}, - 'exchange_rate_pricing_to_billing': {'readonly': True}, - 'payg_cost_in_billing_currency': {'readonly': True}, - 'payg_cost_in_usd': {'readonly': True}, - 'partner_earned_credit_rate': {'readonly': True}, - 'partner_earned_credit_applied': {'readonly': True}, - 'pay_g_price': {'readonly': True}, - 'benefit_id': {'readonly': True}, - 'benefit_name': {'readonly': True}, - 'provider': {'readonly': True}, - 'cost_allocation_rule_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "kind": {"required": True}, + "billing_account_id": {"readonly": True}, + "effective_price": {"readonly": True}, + "pricing_model": {"readonly": True}, + "billing_account_name": {"readonly": True}, + "billing_period_start_date": {"readonly": True}, + "billing_period_end_date": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_name": {"readonly": True}, + "subscription_guid": {"readonly": True}, + "subscription_name": {"readonly": True}, + "date": {"readonly": True}, + "product": {"readonly": True}, + "meter_id": {"readonly": True}, + "meter_name": {"readonly": True}, + "meter_region": {"readonly": True}, + "meter_category": {"readonly": True}, + "meter_sub_category": {"readonly": True}, + "service_family": {"readonly": True}, + "quantity": {"readonly": True}, + "unit_of_measure": {"readonly": True}, + "instance_name": {"readonly": True}, + "cost_in_usd": {"readonly": True}, + "unit_price": {"readonly": True}, + "billing_currency_code": {"readonly": True}, + "resource_location": {"readonly": True}, + "consumed_service": {"readonly": True}, + "service_info1": {"readonly": True}, + "service_info2": {"readonly": True}, + "additional_info": {"readonly": True}, + "invoice_section_id": {"readonly": True}, + "invoice_section_name": {"readonly": True}, + "cost_center": {"readonly": True}, + "resource_group": {"readonly": True}, + "reservation_id": {"readonly": True}, + "reservation_name": {"readonly": True}, + "product_order_id": {"readonly": True}, + "product_order_name": {"readonly": True}, + "is_azure_credit_eligible": {"readonly": True}, + "term": {"readonly": True}, + "publisher_name": {"readonly": True}, + "publisher_type": {"readonly": True}, + "charge_type": {"readonly": True}, + "frequency": {"readonly": True}, + "cost_in_billing_currency": {"readonly": True}, + "cost_in_pricing_currency": {"readonly": True}, + "exchange_rate": {"readonly": True}, + "exchange_rate_date": {"readonly": True}, + "invoice_id": {"readonly": True}, + "previous_invoice_id": {"readonly": True}, + "pricing_currency_code": {"readonly": True}, + "product_identifier": {"readonly": True}, + "resource_location_normalized": {"readonly": True}, + "service_period_start_date": {"readonly": True}, + "service_period_end_date": {"readonly": True}, + "customer_tenant_id": {"readonly": True}, + "customer_name": {"readonly": True}, + "partner_tenant_id": {"readonly": True}, + "partner_name": {"readonly": True}, + "reseller_mpn_id": {"readonly": True}, + "reseller_name": {"readonly": True}, + "publisher_id": {"readonly": True}, + "market_price": {"readonly": True}, + "exchange_rate_pricing_to_billing": {"readonly": True}, + "payg_cost_in_billing_currency": {"readonly": True}, + "payg_cost_in_usd": {"readonly": True}, + "partner_earned_credit_rate": {"readonly": True}, + "partner_earned_credit_applied": {"readonly": True}, + "pay_g_price": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_name": {"readonly": True}, + "provider": {"readonly": True}, + "cost_allocation_rule_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'billing_account_id': {'key': 'properties.billingAccountId', 'type': 'str'}, - 'effective_price': {'key': 'properties.effectivePrice', 'type': 'float'}, - 'pricing_model': {'key': 'properties.pricingModel', 'type': 'str'}, - 'billing_account_name': {'key': 'properties.billingAccountName', 'type': 'str'}, - 'billing_period_start_date': {'key': 'properties.billingPeriodStartDate', 'type': 'iso-8601'}, - 'billing_period_end_date': {'key': 'properties.billingPeriodEndDate', 'type': 'iso-8601'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_name': {'key': 'properties.billingProfileName', 'type': 'str'}, - 'subscription_guid': {'key': 'properties.subscriptionGuid', 'type': 'str'}, - 'subscription_name': {'key': 'properties.subscriptionName', 'type': 'str'}, - 'date': {'key': 'properties.date', 'type': 'iso-8601'}, - 'product': {'key': 'properties.product', 'type': 'str'}, - 'meter_id': {'key': 'properties.meterId', 'type': 'str'}, - 'meter_name': {'key': 'properties.meterName', 'type': 'str'}, - 'meter_region': {'key': 'properties.meterRegion', 'type': 'str'}, - 'meter_category': {'key': 'properties.meterCategory', 'type': 'str'}, - 'meter_sub_category': {'key': 'properties.meterSubCategory', 'type': 'str'}, - 'service_family': {'key': 'properties.serviceFamily', 'type': 'str'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'unit_of_measure': {'key': 'properties.unitOfMeasure', 'type': 'str'}, - 'instance_name': {'key': 'properties.instanceName', 'type': 'str'}, - 'cost_in_usd': {'key': 'properties.costInUSD', 'type': 'float'}, - 'unit_price': {'key': 'properties.unitPrice', 'type': 'float'}, - 'billing_currency_code': {'key': 'properties.billingCurrencyCode', 'type': 'str'}, - 'resource_location': {'key': 'properties.resourceLocation', 'type': 'str'}, - 'consumed_service': {'key': 'properties.consumedService', 'type': 'str'}, - 'service_info1': {'key': 'properties.serviceInfo1', 'type': 'str'}, - 'service_info2': {'key': 'properties.serviceInfo2', 'type': 'str'}, - 'additional_info': {'key': 'properties.additionalInfo', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_name': {'key': 'properties.invoiceSectionName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'resource_group': {'key': 'properties.resourceGroup', 'type': 'str'}, - 'reservation_id': {'key': 'properties.reservationId', 'type': 'str'}, - 'reservation_name': {'key': 'properties.reservationName', 'type': 'str'}, - 'product_order_id': {'key': 'properties.productOrderId', 'type': 'str'}, - 'product_order_name': {'key': 'properties.productOrderName', 'type': 'str'}, - 'is_azure_credit_eligible': {'key': 'properties.isAzureCreditEligible', 'type': 'bool'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'publisher_name': {'key': 'properties.publisherName', 'type': 'str'}, - 'publisher_type': {'key': 'properties.publisherType', 'type': 'str'}, - 'charge_type': {'key': 'properties.chargeType', 'type': 'str'}, - 'frequency': {'key': 'properties.frequency', 'type': 'str'}, - 'cost_in_billing_currency': {'key': 'properties.costInBillingCurrency', 'type': 'float'}, - 'cost_in_pricing_currency': {'key': 'properties.costInPricingCurrency', 'type': 'float'}, - 'exchange_rate': {'key': 'properties.exchangeRate', 'type': 'str'}, - 'exchange_rate_date': {'key': 'properties.exchangeRateDate', 'type': 'iso-8601'}, - 'invoice_id': {'key': 'properties.invoiceId', 'type': 'str'}, - 'previous_invoice_id': {'key': 'properties.previousInvoiceId', 'type': 'str'}, - 'pricing_currency_code': {'key': 'properties.pricingCurrencyCode', 'type': 'str'}, - 'product_identifier': {'key': 'properties.productIdentifier', 'type': 'str'}, - 'resource_location_normalized': {'key': 'properties.resourceLocationNormalized', 'type': 'str'}, - 'service_period_start_date': {'key': 'properties.servicePeriodStartDate', 'type': 'iso-8601'}, - 'service_period_end_date': {'key': 'properties.servicePeriodEndDate', 'type': 'iso-8601'}, - 'customer_tenant_id': {'key': 'properties.customerTenantId', 'type': 'str'}, - 'customer_name': {'key': 'properties.customerName', 'type': 'str'}, - 'partner_tenant_id': {'key': 'properties.partnerTenantId', 'type': 'str'}, - 'partner_name': {'key': 'properties.partnerName', 'type': 'str'}, - 'reseller_mpn_id': {'key': 'properties.resellerMpnId', 'type': 'str'}, - 'reseller_name': {'key': 'properties.resellerName', 'type': 'str'}, - 'publisher_id': {'key': 'properties.publisherId', 'type': 'str'}, - 'market_price': {'key': 'properties.marketPrice', 'type': 'float'}, - 'exchange_rate_pricing_to_billing': {'key': 'properties.exchangeRatePricingToBilling', 'type': 'float'}, - 'payg_cost_in_billing_currency': {'key': 'properties.paygCostInBillingCurrency', 'type': 'float'}, - 'payg_cost_in_usd': {'key': 'properties.paygCostInUSD', 'type': 'float'}, - 'partner_earned_credit_rate': {'key': 'properties.partnerEarnedCreditRate', 'type': 'float'}, - 'partner_earned_credit_applied': {'key': 'properties.partnerEarnedCreditApplied', 'type': 'str'}, - 'pay_g_price': {'key': 'properties.payGPrice', 'type': 'float'}, - 'benefit_id': {'key': 'properties.benefitId', 'type': 'str'}, - 'benefit_name': {'key': 'properties.benefitName', 'type': 'str'}, - 'provider': {'key': 'properties.provider', 'type': 'str'}, - 'cost_allocation_rule_name': {'key': 'properties.costAllocationRuleName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(ModernUsageDetail, self).__init__(**kwargs) - self.kind = 'modern' # type: str + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "kind": {"key": "kind", "type": "str"}, + "billing_account_id": {"key": "properties.billingAccountId", "type": "str"}, + "effective_price": {"key": "properties.effectivePrice", "type": "float"}, + "pricing_model": {"key": "properties.pricingModel", "type": "str"}, + "billing_account_name": {"key": "properties.billingAccountName", "type": "str"}, + "billing_period_start_date": {"key": "properties.billingPeriodStartDate", "type": "iso-8601"}, + "billing_period_end_date": {"key": "properties.billingPeriodEndDate", "type": "iso-8601"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_name": {"key": "properties.billingProfileName", "type": "str"}, + "subscription_guid": {"key": "properties.subscriptionGuid", "type": "str"}, + "subscription_name": {"key": "properties.subscriptionName", "type": "str"}, + "date": {"key": "properties.date", "type": "iso-8601"}, + "product": {"key": "properties.product", "type": "str"}, + "meter_id": {"key": "properties.meterId", "type": "str"}, + "meter_name": {"key": "properties.meterName", "type": "str"}, + "meter_region": {"key": "properties.meterRegion", "type": "str"}, + "meter_category": {"key": "properties.meterCategory", "type": "str"}, + "meter_sub_category": {"key": "properties.meterSubCategory", "type": "str"}, + "service_family": {"key": "properties.serviceFamily", "type": "str"}, + "quantity": {"key": "properties.quantity", "type": "float"}, + "unit_of_measure": {"key": "properties.unitOfMeasure", "type": "str"}, + "instance_name": {"key": "properties.instanceName", "type": "str"}, + "cost_in_usd": {"key": "properties.costInUSD", "type": "float"}, + "unit_price": {"key": "properties.unitPrice", "type": "float"}, + "billing_currency_code": {"key": "properties.billingCurrencyCode", "type": "str"}, + "resource_location": {"key": "properties.resourceLocation", "type": "str"}, + "consumed_service": {"key": "properties.consumedService", "type": "str"}, + "service_info1": {"key": "properties.serviceInfo1", "type": "str"}, + "service_info2": {"key": "properties.serviceInfo2", "type": "str"}, + "additional_info": {"key": "properties.additionalInfo", "type": "str"}, + "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, + "invoice_section_name": {"key": "properties.invoiceSectionName", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "resource_group": {"key": "properties.resourceGroup", "type": "str"}, + "reservation_id": {"key": "properties.reservationId", "type": "str"}, + "reservation_name": {"key": "properties.reservationName", "type": "str"}, + "product_order_id": {"key": "properties.productOrderId", "type": "str"}, + "product_order_name": {"key": "properties.productOrderName", "type": "str"}, + "is_azure_credit_eligible": {"key": "properties.isAzureCreditEligible", "type": "bool"}, + "term": {"key": "properties.term", "type": "str"}, + "publisher_name": {"key": "properties.publisherName", "type": "str"}, + "publisher_type": {"key": "properties.publisherType", "type": "str"}, + "charge_type": {"key": "properties.chargeType", "type": "str"}, + "frequency": {"key": "properties.frequency", "type": "str"}, + "cost_in_billing_currency": {"key": "properties.costInBillingCurrency", "type": "float"}, + "cost_in_pricing_currency": {"key": "properties.costInPricingCurrency", "type": "float"}, + "exchange_rate": {"key": "properties.exchangeRate", "type": "str"}, + "exchange_rate_date": {"key": "properties.exchangeRateDate", "type": "iso-8601"}, + "invoice_id": {"key": "properties.invoiceId", "type": "str"}, + "previous_invoice_id": {"key": "properties.previousInvoiceId", "type": "str"}, + "pricing_currency_code": {"key": "properties.pricingCurrencyCode", "type": "str"}, + "product_identifier": {"key": "properties.productIdentifier", "type": "str"}, + "resource_location_normalized": {"key": "properties.resourceLocationNormalized", "type": "str"}, + "service_period_start_date": {"key": "properties.servicePeriodStartDate", "type": "iso-8601"}, + "service_period_end_date": {"key": "properties.servicePeriodEndDate", "type": "iso-8601"}, + "customer_tenant_id": {"key": "properties.customerTenantId", "type": "str"}, + "customer_name": {"key": "properties.customerName", "type": "str"}, + "partner_tenant_id": {"key": "properties.partnerTenantId", "type": "str"}, + "partner_name": {"key": "properties.partnerName", "type": "str"}, + "reseller_mpn_id": {"key": "properties.resellerMpnId", "type": "str"}, + "reseller_name": {"key": "properties.resellerName", "type": "str"}, + "publisher_id": {"key": "properties.publisherId", "type": "str"}, + "market_price": {"key": "properties.marketPrice", "type": "float"}, + "exchange_rate_pricing_to_billing": {"key": "properties.exchangeRatePricingToBilling", "type": "float"}, + "payg_cost_in_billing_currency": {"key": "properties.paygCostInBillingCurrency", "type": "float"}, + "payg_cost_in_usd": {"key": "properties.paygCostInUSD", "type": "float"}, + "partner_earned_credit_rate": {"key": "properties.partnerEarnedCreditRate", "type": "float"}, + "partner_earned_credit_applied": {"key": "properties.partnerEarnedCreditApplied", "type": "str"}, + "pay_g_price": {"key": "properties.payGPrice", "type": "float"}, + "benefit_id": {"key": "properties.benefitId", "type": "str"}, + "benefit_name": {"key": "properties.benefitName", "type": "str"}, + "provider": {"key": "properties.provider", "type": "str"}, + "cost_allocation_rule_name": {"key": "properties.costAllocationRuleName", "type": "str"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) + self.kind: str = "modern" self.billing_account_id = None self.effective_price = None self.pricing_model = None @@ -4065,23 +4204,23 @@ def __init__( self.cost_allocation_rule_name = None -class Notification(msrest.serialization.Model): +class Notification(_serialization.Model): """The notification associated with a budget. All required parameters must be populated in order to send to Azure. - :ivar enabled: Required. The notification is enabled or not. + :ivar enabled: The notification is enabled or not. Required. :vartype enabled: bool - :ivar operator: Required. The comparison operator. Known values are: "EqualTo", "GreaterThan", - "GreaterThanOrEqualTo". + :ivar operator: The comparison operator. Required. Known values are: "EqualTo", "GreaterThan", + and "GreaterThanOrEqualTo". :vartype operator: str or ~azure.mgmt.consumption.models.OperatorType - :ivar threshold: Required. Threshold value associated with a notification. Notification is sent - when the cost exceeded the threshold. It is always percent and has to be between 0 and 1000. + :ivar threshold: Threshold value associated with a notification. Notification is sent when the + cost exceeded the threshold. It is always percent and has to be between 0 and 1000. Required. :vartype threshold: float - :ivar contact_emails: Required. Email addresses to send the budget notification to when the - threshold is exceeded. Must have at least one contact email or contact group specified at the - Subscription or Resource Group scopes. All other scopes must have at least one contact email - specified. + :ivar contact_emails: Email addresses to send the budget notification to when the threshold is + exceeded. Must have at least one contact email or contact group specified at the Subscription + or Resource Group scopes. All other scopes must have at least one contact email specified. + Required. :vartype contact_emails: list[str] :ivar contact_roles: Contact roles to send the budget notification to when the threshold is exceeded. @@ -4090,33 +4229,32 @@ class Notification(msrest.serialization.Model): exceeded. Must be provided as a fully qualified Azure resource id. Only supported at Subscription or Resource Group scopes. :vartype contact_groups: list[str] - :ivar threshold_type: The type of threshold. Known values are: "Actual", "Forecasted". Default - value: "Actual". + :ivar threshold_type: The type of threshold. Known values are: "Actual" and "Forecasted". :vartype threshold_type: str or ~azure.mgmt.consumption.models.ThresholdType :ivar locale: Language in which the recipient will receive the notification. Known values are: "en-us", "ja-jp", "zh-cn", "de-de", "es-es", "fr-fr", "it-it", "ko-kr", "pt-br", "ru-ru", - "zh-tw", "cs-cz", "pl-pl", "tr-tr", "da-dk", "en-gb", "hu-hu", "nb-no", "nl-nl", "pt-pt", + "zh-tw", "cs-cz", "pl-pl", "tr-tr", "da-dk", "en-gb", "hu-hu", "nb-no", "nl-nl", "pt-pt", and "sv-se". :vartype locale: str or ~azure.mgmt.consumption.models.CultureCode """ _validation = { - 'enabled': {'required': True}, - 'operator': {'required': True}, - 'threshold': {'required': True}, - 'contact_emails': {'required': True, 'max_items': 50, 'min_items': 0}, - 'contact_groups': {'max_items': 50, 'min_items': 0}, + "enabled": {"required": True}, + "operator": {"required": True}, + "threshold": {"required": True}, + "contact_emails": {"required": True, "max_items": 50, "min_items": 0}, + "contact_groups": {"max_items": 50, "min_items": 0}, } _attribute_map = { - 'enabled': {'key': 'enabled', 'type': 'bool'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'threshold': {'key': 'threshold', 'type': 'float'}, - 'contact_emails': {'key': 'contactEmails', 'type': '[str]'}, - 'contact_roles': {'key': 'contactRoles', 'type': '[str]'}, - 'contact_groups': {'key': 'contactGroups', 'type': '[str]'}, - 'threshold_type': {'key': 'thresholdType', 'type': 'str'}, - 'locale': {'key': 'locale', 'type': 'str'}, + "enabled": {"key": "enabled", "type": "bool"}, + "operator": {"key": "operator", "type": "str"}, + "threshold": {"key": "threshold", "type": "float"}, + "contact_emails": {"key": "contactEmails", "type": "[str]"}, + "contact_roles": {"key": "contactRoles", "type": "[str]"}, + "contact_groups": {"key": "contactGroups", "type": "[str]"}, + "threshold_type": {"key": "thresholdType", "type": "str"}, + "locale": {"key": "locale", "type": "str"}, } def __init__( @@ -4128,24 +4266,24 @@ def __init__( contact_emails: List[str], contact_roles: Optional[List[str]] = None, contact_groups: Optional[List[str]] = None, - threshold_type: Optional[Union[str, "_models.ThresholdType"]] = "Actual", + threshold_type: Union[str, "_models.ThresholdType"] = "Actual", locale: Optional[Union[str, "_models.CultureCode"]] = None, **kwargs ): """ - :keyword enabled: Required. The notification is enabled or not. + :keyword enabled: The notification is enabled or not. Required. :paramtype enabled: bool - :keyword operator: Required. The comparison operator. Known values are: "EqualTo", - "GreaterThan", "GreaterThanOrEqualTo". + :keyword operator: The comparison operator. Required. Known values are: "EqualTo", + "GreaterThan", and "GreaterThanOrEqualTo". :paramtype operator: str or ~azure.mgmt.consumption.models.OperatorType - :keyword threshold: Required. Threshold value associated with a notification. Notification is - sent when the cost exceeded the threshold. It is always percent and has to be between 0 and - 1000. + :keyword threshold: Threshold value associated with a notification. Notification is sent when + the cost exceeded the threshold. It is always percent and has to be between 0 and 1000. + Required. :paramtype threshold: float - :keyword contact_emails: Required. Email addresses to send the budget notification to when the - threshold is exceeded. Must have at least one contact email or contact group specified at the + :keyword contact_emails: Email addresses to send the budget notification to when the threshold + is exceeded. Must have at least one contact email or contact group specified at the Subscription or Resource Group scopes. All other scopes must have at least one contact email - specified. + specified. Required. :paramtype contact_emails: list[str] :keyword contact_roles: Contact roles to send the budget notification to when the threshold is exceeded. @@ -4154,16 +4292,15 @@ def __init__( exceeded. Must be provided as a fully qualified Azure resource id. Only supported at Subscription or Resource Group scopes. :paramtype contact_groups: list[str] - :keyword threshold_type: The type of threshold. Known values are: "Actual", "Forecasted". - Default value: "Actual". + :keyword threshold_type: The type of threshold. Known values are: "Actual" and "Forecasted". :paramtype threshold_type: str or ~azure.mgmt.consumption.models.ThresholdType :keyword locale: Language in which the recipient will receive the notification. Known values are: "en-us", "ja-jp", "zh-cn", "de-de", "es-es", "fr-fr", "it-it", "ko-kr", "pt-br", "ru-ru", - "zh-tw", "cs-cz", "pl-pl", "tr-tr", "da-dk", "en-gb", "hu-hu", "nb-no", "nl-nl", "pt-pt", + "zh-tw", "cs-cz", "pl-pl", "tr-tr", "da-dk", "en-gb", "hu-hu", "nb-no", "nl-nl", "pt-pt", and "sv-se". :paramtype locale: str or ~azure.mgmt.consumption.models.CultureCode """ - super(Notification, self).__init__(**kwargs) + super().__init__(**kwargs) self.enabled = enabled self.operator = operator self.threshold = threshold @@ -4174,7 +4311,7 @@ def __init__( self.locale = locale -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """A Consumption REST API operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -4188,33 +4325,28 @@ class Operation(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, } - def __init__( - self, - *, - display: Optional["_models.OperationDisplay"] = None, - **kwargs - ): + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): """ :keyword display: The object that represents the operation. :paramtype display: ~azure.mgmt.consumption.models.OperationDisplay """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.display = display -class OperationDisplay(msrest.serialization.Model): +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. @@ -4230,33 +4362,29 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """Result of listing consumption 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. @@ -4269,27 +4397,23 @@ class OperationListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PriceSheetProperties(msrest.serialization.Model): +class PriceSheetProperties(_serialization.Model): """The properties of the price sheet. Variables are only populated by the server, and will be ignored when sending a request. @@ -4316,36 +4440,32 @@ class PriceSheetProperties(msrest.serialization.Model): """ _validation = { - 'billing_period_id': {'readonly': True}, - 'meter_id': {'readonly': True}, - 'meter_details': {'readonly': True}, - 'unit_of_measure': {'readonly': True}, - 'included_quantity': {'readonly': True}, - 'part_number': {'readonly': True}, - 'unit_price': {'readonly': True}, - 'currency_code': {'readonly': True}, - 'offer_id': {'readonly': True}, + "billing_period_id": {"readonly": True}, + "meter_id": {"readonly": True}, + "meter_details": {"readonly": True}, + "unit_of_measure": {"readonly": True}, + "included_quantity": {"readonly": True}, + "part_number": {"readonly": True}, + "unit_price": {"readonly": True}, + "currency_code": {"readonly": True}, + "offer_id": {"readonly": True}, } _attribute_map = { - 'billing_period_id': {'key': 'billingPeriodId', 'type': 'str'}, - 'meter_id': {'key': 'meterId', 'type': 'str'}, - 'meter_details': {'key': 'meterDetails', 'type': 'MeterDetails'}, - 'unit_of_measure': {'key': 'unitOfMeasure', 'type': 'str'}, - 'included_quantity': {'key': 'includedQuantity', 'type': 'float'}, - 'part_number': {'key': 'partNumber', 'type': 'str'}, - 'unit_price': {'key': 'unitPrice', 'type': 'float'}, - 'currency_code': {'key': 'currencyCode', 'type': 'str'}, - 'offer_id': {'key': 'offerId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(PriceSheetProperties, self).__init__(**kwargs) + "billing_period_id": {"key": "billingPeriodId", "type": "str"}, + "meter_id": {"key": "meterId", "type": "str"}, + "meter_details": {"key": "meterDetails", "type": "MeterDetails"}, + "unit_of_measure": {"key": "unitOfMeasure", "type": "str"}, + "included_quantity": {"key": "includedQuantity", "type": "float"}, + "part_number": {"key": "partNumber", "type": "str"}, + "unit_price": {"key": "unitPrice", "type": "float"}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "offer_id": {"key": "offerId", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.billing_period_id = None self.meter_id = None self.meter_details = None @@ -4370,7 +4490,7 @@ class PriceSheetResult(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar pricesheets: Price sheet. :vartype pricesheets: list[~azure.mgmt.consumption.models.PriceSheetProperties] @@ -4381,40 +4501,36 @@ class PriceSheetResult(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'pricesheets': {'readonly': True}, - 'next_link': {'readonly': True}, - 'download': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "pricesheets": {"readonly": True}, + "next_link": {"readonly": True}, + "download": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'pricesheets': {'key': 'properties.pricesheets', 'type': '[PriceSheetProperties]'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - 'download': {'key': 'properties.download', 'type': 'MeterDetails'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(PriceSheetResult, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "pricesheets": {"key": "properties.pricesheets", "type": "[PriceSheetProperties]"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + "download": {"key": "properties.download", "type": "MeterDetails"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.pricesheets = None self.next_link = None self.download = None -class Reseller(msrest.serialization.Model): +class Reseller(_serialization.Model): """The reseller properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -4426,27 +4542,23 @@ class Reseller(msrest.serialization.Model): """ _validation = { - 'reseller_id': {'readonly': True}, - 'reseller_description': {'readonly': True}, + "reseller_id": {"readonly": True}, + "reseller_description": {"readonly": True}, } _attribute_map = { - 'reseller_id': {'key': 'resellerId', 'type': 'str'}, - 'reseller_description': {'key': 'resellerDescription', 'type': 'str'}, + "reseller_id": {"key": "resellerId", "type": "str"}, + "reseller_description": {"key": "resellerDescription", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Reseller, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.reseller_id = None self.reseller_description = None -class ReservationDetail(Resource): +class ReservationDetail(Resource): # pylint: disable=too-many-instance-attributes """reservation detail resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -4459,7 +4571,7 @@ class ReservationDetail(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar reservation_order_id: The reservation order ID is the identifier for a reservation purchase. Each reservation order ID represents a single purchase transaction. A reservation @@ -4496,50 +4608,46 @@ class ReservationDetail(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'reservation_order_id': {'readonly': True}, - 'instance_flexibility_ratio': {'readonly': True}, - 'instance_flexibility_group': {'readonly': True}, - 'reservation_id': {'readonly': True}, - 'sku_name': {'readonly': True}, - 'reserved_hours': {'readonly': True}, - 'usage_date': {'readonly': True}, - 'used_hours': {'readonly': True}, - 'instance_id': {'readonly': True}, - 'total_reserved_quantity': {'readonly': True}, - 'kind': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "reservation_order_id": {"readonly": True}, + "instance_flexibility_ratio": {"readonly": True}, + "instance_flexibility_group": {"readonly": True}, + "reservation_id": {"readonly": True}, + "sku_name": {"readonly": True}, + "reserved_hours": {"readonly": True}, + "usage_date": {"readonly": True}, + "used_hours": {"readonly": True}, + "instance_id": {"readonly": True}, + "total_reserved_quantity": {"readonly": True}, + "kind": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'reservation_order_id': {'key': 'properties.reservationOrderId', 'type': 'str'}, - 'instance_flexibility_ratio': {'key': 'properties.instanceFlexibilityRatio', 'type': 'str'}, - 'instance_flexibility_group': {'key': 'properties.instanceFlexibilityGroup', 'type': 'str'}, - 'reservation_id': {'key': 'properties.reservationId', 'type': 'str'}, - 'sku_name': {'key': 'properties.skuName', 'type': 'str'}, - 'reserved_hours': {'key': 'properties.reservedHours', 'type': 'float'}, - 'usage_date': {'key': 'properties.usageDate', 'type': 'iso-8601'}, - 'used_hours': {'key': 'properties.usedHours', 'type': 'float'}, - 'instance_id': {'key': 'properties.instanceId', 'type': 'str'}, - 'total_reserved_quantity': {'key': 'properties.totalReservedQuantity', 'type': 'float'}, - 'kind': {'key': 'properties.kind', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationDetail, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"}, + "instance_flexibility_ratio": {"key": "properties.instanceFlexibilityRatio", "type": "str"}, + "instance_flexibility_group": {"key": "properties.instanceFlexibilityGroup", "type": "str"}, + "reservation_id": {"key": "properties.reservationId", "type": "str"}, + "sku_name": {"key": "properties.skuName", "type": "str"}, + "reserved_hours": {"key": "properties.reservedHours", "type": "float"}, + "usage_date": {"key": "properties.usageDate", "type": "iso-8601"}, + "used_hours": {"key": "properties.usedHours", "type": "float"}, + "instance_id": {"key": "properties.instanceId", "type": "str"}, + "total_reserved_quantity": {"key": "properties.totalReservedQuantity", "type": "float"}, + "kind": {"key": "properties.kind", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.reservation_order_id = None self.instance_flexibility_ratio = None self.instance_flexibility_group = None @@ -4553,7 +4661,7 @@ def __init__( self.kind = None -class ReservationDetailsListResult(msrest.serialization.Model): +class ReservationDetailsListResult(_serialization.Model): """Result of listing reservation details. Variables are only populated by the server, and will be ignored when sending a request. @@ -4565,79 +4673,72 @@ class ReservationDetailsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ReservationDetail]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ReservationDetail]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationDetailsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class ReservationRecommendationDetailsCalculatedSavingsProperties(msrest.serialization.Model): - """Details of estimated savings. +class ReservationRecommendationDetailsCalculatedSavingsProperties(_serialization.Model): + """Details of estimated savings. The costs and savings are estimated for the term. Variables are only populated by the server, and will be ignored when sending a request. - :ivar on_demand_cost: The cost without reservation. + :ivar on_demand_cost: The cost without reservation. Includes hardware and software cost. :vartype on_demand_cost: float - :ivar overage_cost: The difference between total reservation cost and reservation cost. + :ivar overage_cost: Hardware and software cost of the resources not covered by the reservation. :vartype overage_cost: float :ivar quantity: The quantity for calculated savings. :vartype quantity: float - :ivar reservation_cost: The exact cost of the estimated usage using reservation. + :ivar reservation_cost: Hardware cost of the resources covered by the reservation. :vartype reservation_cost: float - :ivar total_reservation_cost: The cost of the suggested quantity. + :ivar total_reservation_cost: Reservation cost + software cost of the resources covered by the + reservation + overage cost. :vartype total_reservation_cost: float :ivar reserved_unit_count: The number of reserved units used to calculate savings. Always 1 for virtual machines. :vartype reserved_unit_count: float - :ivar savings: The amount saved by purchasing the recommended quantity of reservation. + :ivar savings: The amount saved by purchasing the recommended quantity of reservation. This is + equal to onDemandCost - totalReservationCost. :vartype savings: float """ _validation = { - 'on_demand_cost': {'readonly': True}, - 'overage_cost': {'readonly': True}, - 'quantity': {'readonly': True}, - 'reservation_cost': {'readonly': True}, - 'total_reservation_cost': {'readonly': True}, - 'savings': {'readonly': True}, + "on_demand_cost": {"readonly": True}, + "overage_cost": {"readonly": True}, + "quantity": {"readonly": True}, + "reservation_cost": {"readonly": True}, + "total_reservation_cost": {"readonly": True}, + "savings": {"readonly": True}, } _attribute_map = { - 'on_demand_cost': {'key': 'onDemandCost', 'type': 'float'}, - 'overage_cost': {'key': 'overageCost', 'type': 'float'}, - 'quantity': {'key': 'quantity', 'type': 'float'}, - 'reservation_cost': {'key': 'reservationCost', 'type': 'float'}, - 'total_reservation_cost': {'key': 'totalReservationCost', 'type': 'float'}, - 'reserved_unit_count': {'key': 'reservedUnitCount', 'type': 'float'}, - 'savings': {'key': 'savings', 'type': 'float'}, + "on_demand_cost": {"key": "onDemandCost", "type": "float"}, + "overage_cost": {"key": "overageCost", "type": "float"}, + "quantity": {"key": "quantity", "type": "float"}, + "reservation_cost": {"key": "reservationCost", "type": "float"}, + "total_reservation_cost": {"key": "totalReservationCost", "type": "float"}, + "reserved_unit_count": {"key": "reservedUnitCount", "type": "float"}, + "savings": {"key": "savings", "type": "float"}, } - def __init__( - self, - *, - reserved_unit_count: Optional[float] = None, - **kwargs - ): + def __init__(self, *, reserved_unit_count: Optional[float] = None, **kwargs): """ :keyword reserved_unit_count: The number of reserved units used to calculate savings. Always 1 for virtual machines. :paramtype reserved_unit_count: float """ - super(ReservationRecommendationDetailsCalculatedSavingsProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.on_demand_cost = None self.overage_cost = None self.quantity = None @@ -4647,7 +4748,7 @@ def __init__( self.savings = None -class ReservationRecommendationDetailsModel(Resource): +class ReservationRecommendationDetailsModel(Resource): # pylint: disable=too-many-instance-attributes """Reservation recommendation details. Variables are only populated by the server, and will be ignored when sending a request. @@ -4660,7 +4761,7 @@ class ReservationRecommendationDetailsModel(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar location: Resource Location. :vartype location: str @@ -4683,49 +4784,43 @@ class ReservationRecommendationDetailsModel(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'currency': {'readonly': True}, - 'resource': {'readonly': True}, - 'resource_group': {'readonly': True}, - 'savings': {'readonly': True}, - 'scope': {'readonly': True}, - 'usage': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "currency": {"readonly": True}, + "resource": {"readonly": True}, + "resource_group": {"readonly": True}, + "savings": {"readonly": True}, + "scope": {"readonly": True}, + "usage": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'resource': {'key': 'properties.resource', 'type': 'ReservationRecommendationDetailsResourceProperties'}, - 'resource_group': {'key': 'properties.resourceGroup', 'type': 'str'}, - 'savings': {'key': 'properties.savings', 'type': 'ReservationRecommendationDetailsSavingsProperties'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'usage': {'key': 'properties.usage', 'type': 'ReservationRecommendationDetailsUsageProperties'}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - sku: Optional[str] = None, - **kwargs - ): + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "currency": {"key": "properties.currency", "type": "str"}, + "resource": {"key": "properties.resource", "type": "ReservationRecommendationDetailsResourceProperties"}, + "resource_group": {"key": "properties.resourceGroup", "type": "str"}, + "savings": {"key": "properties.savings", "type": "ReservationRecommendationDetailsSavingsProperties"}, + "scope": {"key": "properties.scope", "type": "str"}, + "usage": {"key": "properties.usage", "type": "ReservationRecommendationDetailsUsageProperties"}, + } + + def __init__(self, *, location: Optional[str] = None, sku: Optional[str] = None, **kwargs): """ :keyword location: Resource Location. :paramtype location: str :keyword sku: Resource sku. :paramtype sku: str """ - super(ReservationRecommendationDetailsModel, self).__init__(**kwargs) + super().__init__(**kwargs) self.location = location self.sku = sku self.currency = None @@ -4736,50 +4831,47 @@ def __init__( self.usage = None -class ReservationRecommendationDetailsResourceProperties(msrest.serialization.Model): +class ReservationRecommendationDetailsResourceProperties(_serialization.Model): """Details of the resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar applied_scopes: List of subscriptions for which the reservation is applied. :vartype applied_scopes: list[str] - :ivar on_demand_rate: On demand rate of the resource. + :ivar on_demand_rate: Hourly on-demand rate of the resource. Includes only hardware rate i.e, + software rate is not included. :vartype on_demand_rate: float :ivar product: Azure product ex: Standard_E8s_v3 etc. :vartype product: str :ivar region: Azure resource region ex:EastUS, WestUS etc. :vartype region: str - :ivar reservation_rate: Reservation rate of the resource. + :ivar reservation_rate: Hourly reservation rate of the resource. Varies based on the term. :vartype reservation_rate: float :ivar resource_type: The azure resource type. :vartype resource_type: str """ _validation = { - 'applied_scopes': {'readonly': True}, - 'on_demand_rate': {'readonly': True}, - 'product': {'readonly': True}, - 'region': {'readonly': True}, - 'reservation_rate': {'readonly': True}, - 'resource_type': {'readonly': True}, + "applied_scopes": {"readonly": True}, + "on_demand_rate": {"readonly": True}, + "product": {"readonly": True}, + "region": {"readonly": True}, + "reservation_rate": {"readonly": True}, + "resource_type": {"readonly": True}, } _attribute_map = { - 'applied_scopes': {'key': 'appliedScopes', 'type': '[str]'}, - 'on_demand_rate': {'key': 'onDemandRate', 'type': 'float'}, - 'product': {'key': 'product', 'type': 'str'}, - 'region': {'key': 'region', 'type': 'str'}, - 'reservation_rate': {'key': 'reservationRate', 'type': 'float'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, + "applied_scopes": {"key": "appliedScopes", "type": "[str]"}, + "on_demand_rate": {"key": "onDemandRate", "type": "float"}, + "product": {"key": "product", "type": "str"}, + "region": {"key": "region", "type": "str"}, + "reservation_rate": {"key": "reservationRate", "type": "float"}, + "resource_type": {"key": "resourceType", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationRecommendationDetailsResourceProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.applied_scopes = None self.on_demand_rate = None self.product = None @@ -4788,7 +4880,7 @@ def __init__( self.resource_type = None -class ReservationRecommendationDetailsSavingsProperties(msrest.serialization.Model): +class ReservationRecommendationDetailsSavingsProperties(_serialization.Model): """Details of the estimated savings. Variables are only populated by the server, and will be ignored when sending a request. @@ -4810,26 +4902,31 @@ class ReservationRecommendationDetailsSavingsProperties(msrest.serialization.Mod """ _validation = { - 'look_back_period': {'readonly': True}, - 'recommended_quantity': {'readonly': True}, - 'reservation_order_term': {'readonly': True}, - 'savings_type': {'readonly': True}, - 'unit_of_measure': {'readonly': True}, + "look_back_period": {"readonly": True}, + "recommended_quantity": {"readonly": True}, + "reservation_order_term": {"readonly": True}, + "savings_type": {"readonly": True}, + "unit_of_measure": {"readonly": True}, } _attribute_map = { - 'calculated_savings': {'key': 'calculatedSavings', 'type': '[ReservationRecommendationDetailsCalculatedSavingsProperties]'}, - 'look_back_period': {'key': 'lookBackPeriod', 'type': 'int'}, - 'recommended_quantity': {'key': 'recommendedQuantity', 'type': 'float'}, - 'reservation_order_term': {'key': 'reservationOrderTerm', 'type': 'str'}, - 'savings_type': {'key': 'savingsType', 'type': 'str'}, - 'unit_of_measure': {'key': 'unitOfMeasure', 'type': 'str'}, + "calculated_savings": { + "key": "calculatedSavings", + "type": "[ReservationRecommendationDetailsCalculatedSavingsProperties]", + }, + "look_back_period": {"key": "lookBackPeriod", "type": "int"}, + "recommended_quantity": {"key": "recommendedQuantity", "type": "float"}, + "reservation_order_term": {"key": "reservationOrderTerm", "type": "str"}, + "savings_type": {"key": "savingsType", "type": "str"}, + "unit_of_measure": {"key": "unitOfMeasure", "type": "str"}, } def __init__( self, *, - calculated_savings: Optional[List["_models.ReservationRecommendationDetailsCalculatedSavingsProperties"]] = None, + calculated_savings: Optional[ + List["_models.ReservationRecommendationDetailsCalculatedSavingsProperties"] + ] = None, **kwargs ): """ @@ -4837,7 +4934,7 @@ def __init__( :paramtype calculated_savings: list[~azure.mgmt.consumption.models.ReservationRecommendationDetailsCalculatedSavingsProperties] """ - super(ReservationRecommendationDetailsSavingsProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.calculated_savings = calculated_savings self.look_back_period = None self.recommended_quantity = None @@ -4846,7 +4943,7 @@ def __init__( self.unit_of_measure = None -class ReservationRecommendationDetailsUsageProperties(msrest.serialization.Model): +class ReservationRecommendationDetailsUsageProperties(_serialization.Model): """Details about historical usage data that has been used for computing the recommendation. Variables are only populated by the server, and will be ignored when sending a request. @@ -4867,28 +4964,24 @@ class ReservationRecommendationDetailsUsageProperties(msrest.serialization.Model """ _validation = { - 'first_consumption_date': {'readonly': True}, - 'last_consumption_date': {'readonly': True}, - 'look_back_unit_type': {'readonly': True}, - 'usage_data': {'readonly': True}, - 'usage_grain': {'readonly': True}, + "first_consumption_date": {"readonly": True}, + "last_consumption_date": {"readonly": True}, + "look_back_unit_type": {"readonly": True}, + "usage_data": {"readonly": True}, + "usage_grain": {"readonly": True}, } _attribute_map = { - 'first_consumption_date': {'key': 'firstConsumptionDate', 'type': 'str'}, - 'last_consumption_date': {'key': 'lastConsumptionDate', 'type': 'str'}, - 'look_back_unit_type': {'key': 'lookBackUnitType', 'type': 'str'}, - 'usage_data': {'key': 'usageData', 'type': '[float]'}, - 'usage_grain': {'key': 'usageGrain', 'type': 'str'}, + "first_consumption_date": {"key": "firstConsumptionDate", "type": "str"}, + "last_consumption_date": {"key": "lastConsumptionDate", "type": "str"}, + "look_back_unit_type": {"key": "lookBackUnitType", "type": "str"}, + "usage_data": {"key": "usageData", "type": "[float]"}, + "usage_grain": {"key": "usageGrain", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationRecommendationDetailsUsageProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.first_consumption_date = None self.last_consumption_date = None self.look_back_unit_type = None @@ -4896,7 +4989,7 @@ def __init__( self.usage_grain = None -class ReservationRecommendationsListResult(msrest.serialization.Model): +class ReservationRecommendationsListResult(_serialization.Model): """Result of listing reservation recommendations. Variables are only populated by the server, and will be ignored when sending a request. @@ -4910,30 +5003,26 @@ class ReservationRecommendationsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - 'previous_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, + "previous_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ReservationRecommendation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'previous_link': {'key': 'previousLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ReservationRecommendation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + "previous_link": {"key": "previousLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationRecommendationsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None self.previous_link = None -class ReservationSummariesListResult(msrest.serialization.Model): +class ReservationSummariesListResult(_serialization.Model): """Result of listing reservation summaries. Variables are only populated by the server, and will be ignored when sending a request. @@ -4945,27 +5034,23 @@ class ReservationSummariesListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ReservationSummary]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ReservationSummary]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationSummariesListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class ReservationSummary(Resource): +class ReservationSummary(Resource): # pylint: disable=too-many-instance-attributes """reservation summary resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -4978,7 +5063,7 @@ class ReservationSummary(Resource): :vartype type: str :ivar etag: The etag for the resource. :vartype etag: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] :ivar reservation_order_id: The reservation order ID is the identifier for a reservation purchase. Each reservation order ID represents a single purchase transaction. A reservation @@ -5027,58 +5112,54 @@ class ReservationSummary(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'etag': {'readonly': True}, - 'tags': {'readonly': True}, - 'reservation_order_id': {'readonly': True}, - 'reservation_id': {'readonly': True}, - 'sku_name': {'readonly': True}, - 'reserved_hours': {'readonly': True}, - 'usage_date': {'readonly': True}, - 'used_hours': {'readonly': True}, - 'min_utilization_percentage': {'readonly': True}, - 'avg_utilization_percentage': {'readonly': True}, - 'max_utilization_percentage': {'readonly': True}, - 'kind': {'readonly': True}, - 'purchased_quantity': {'readonly': True}, - 'remaining_quantity': {'readonly': True}, - 'total_reserved_quantity': {'readonly': True}, - 'used_quantity': {'readonly': True}, - 'utilized_percentage': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "etag": {"readonly": True}, + "tags": {"readonly": True}, + "reservation_order_id": {"readonly": True}, + "reservation_id": {"readonly": True}, + "sku_name": {"readonly": True}, + "reserved_hours": {"readonly": True}, + "usage_date": {"readonly": True}, + "used_hours": {"readonly": True}, + "min_utilization_percentage": {"readonly": True}, + "avg_utilization_percentage": {"readonly": True}, + "max_utilization_percentage": {"readonly": True}, + "kind": {"readonly": True}, + "purchased_quantity": {"readonly": True}, + "remaining_quantity": {"readonly": True}, + "total_reserved_quantity": {"readonly": True}, + "used_quantity": {"readonly": True}, + "utilized_percentage": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'etag': {'key': 'etag', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'reservation_order_id': {'key': 'properties.reservationOrderId', 'type': 'str'}, - 'reservation_id': {'key': 'properties.reservationId', 'type': 'str'}, - 'sku_name': {'key': 'properties.skuName', 'type': 'str'}, - 'reserved_hours': {'key': 'properties.reservedHours', 'type': 'float'}, - 'usage_date': {'key': 'properties.usageDate', 'type': 'iso-8601'}, - 'used_hours': {'key': 'properties.usedHours', 'type': 'float'}, - 'min_utilization_percentage': {'key': 'properties.minUtilizationPercentage', 'type': 'float'}, - 'avg_utilization_percentage': {'key': 'properties.avgUtilizationPercentage', 'type': 'float'}, - 'max_utilization_percentage': {'key': 'properties.maxUtilizationPercentage', 'type': 'float'}, - 'kind': {'key': 'properties.kind', 'type': 'str'}, - 'purchased_quantity': {'key': 'properties.purchasedQuantity', 'type': 'float'}, - 'remaining_quantity': {'key': 'properties.remainingQuantity', 'type': 'float'}, - 'total_reserved_quantity': {'key': 'properties.totalReservedQuantity', 'type': 'float'}, - 'used_quantity': {'key': 'properties.usedQuantity', 'type': 'float'}, - 'utilized_percentage': {'key': 'properties.utilizedPercentage', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationSummary, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "reservation_order_id": {"key": "properties.reservationOrderId", "type": "str"}, + "reservation_id": {"key": "properties.reservationId", "type": "str"}, + "sku_name": {"key": "properties.skuName", "type": "str"}, + "reserved_hours": {"key": "properties.reservedHours", "type": "float"}, + "usage_date": {"key": "properties.usageDate", "type": "iso-8601"}, + "used_hours": {"key": "properties.usedHours", "type": "float"}, + "min_utilization_percentage": {"key": "properties.minUtilizationPercentage", "type": "float"}, + "avg_utilization_percentage": {"key": "properties.avgUtilizationPercentage", "type": "float"}, + "max_utilization_percentage": {"key": "properties.maxUtilizationPercentage", "type": "float"}, + "kind": {"key": "properties.kind", "type": "str"}, + "purchased_quantity": {"key": "properties.purchasedQuantity", "type": "float"}, + "remaining_quantity": {"key": "properties.remainingQuantity", "type": "float"}, + "total_reserved_quantity": {"key": "properties.totalReservedQuantity", "type": "float"}, + "used_quantity": {"key": "properties.usedQuantity", "type": "float"}, + "utilized_percentage": {"key": "properties.utilizedPercentage", "type": "float"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.reservation_order_id = None self.reservation_id = None self.sku_name = None @@ -5096,7 +5177,7 @@ def __init__( self.utilized_percentage = None -class ReservationTransactionsListResult(msrest.serialization.Model): +class ReservationTransactionsListResult(_serialization.Model): """Result of listing reservation recommendations. Variables are only populated by the server, and will be ignored when sending a request. @@ -5108,27 +5189,23 @@ class ReservationTransactionsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ReservationTransaction]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ReservationTransaction]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ReservationTransactionsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class SkuProperty(msrest.serialization.Model): +class SkuProperty(_serialization.Model): """The Sku property. Variables are only populated by the server, and will be ignored when sending a request. @@ -5140,27 +5217,23 @@ class SkuProperty(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'value': {'readonly': True}, + "name": {"readonly": True}, + "value": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(SkuProperty, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.value = None -class Tag(msrest.serialization.Model): +class Tag(_serialization.Model): """The tag resource. :ivar key: Tag key. @@ -5170,24 +5243,18 @@ class Tag(msrest.serialization.Model): """ _attribute_map = { - 'key': {'key': 'key', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[str]'}, + "key": {"key": "key", "type": "str"}, + "value": {"key": "value", "type": "[str]"}, } - def __init__( - self, - *, - key: Optional[str] = None, - value: Optional[List[str]] = None, - **kwargs - ): + def __init__(self, *, key: Optional[str] = None, value: Optional[List[str]] = None, **kwargs): """ :keyword key: Tag key. :paramtype key: str :keyword value: Tag values. :paramtype value: list[str] """ - super(Tag, self).__init__(**kwargs) + super().__init__(**kwargs) self.key = key self.value = value @@ -5206,7 +5273,7 @@ class TagsResult(ProxyResource): :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 tags: A set of tags. A list of Tag. + :ivar tags: A list of Tag. :vartype tags: list[~azure.mgmt.consumption.models.Tag] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str @@ -5215,44 +5282,38 @@ class TagsResult(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'next_link': {'readonly': True}, - 'previous_link': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "next_link": {"readonly": True}, + "previous_link": {"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'}, - 'tags': {'key': 'properties.tags', 'type': '[Tag]'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - 'previous_link': {'key': 'properties.previousLink', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "properties.tags", "type": "[Tag]"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + "previous_link": {"key": "properties.previousLink", "type": "str"}, } - def __init__( - self, - *, - e_tag: Optional[str] = None, - tags: Optional[List["_models.Tag"]] = None, - **kwargs - ): + def __init__(self, *, e_tag: Optional[str] = None, tags: Optional[List["_models.Tag"]] = 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 - :keyword tags: A set of tags. A list of Tag. + :keyword tags: A list of Tag. :paramtype tags: list[~azure.mgmt.consumption.models.Tag] """ - super(TagsResult, self).__init__(e_tag=e_tag, **kwargs) + super().__init__(e_tag=e_tag, **kwargs) self.tags = tags self.next_link = None self.previous_link = None -class UsageDetailsListResult(msrest.serialization.Model): +class UsageDetailsListResult(_serialization.Model): """Result of listing usage details. It contains a list of available usage details in reverse chronological order by billing period. Variables are only populated by the server, and will be ignored when sending a request. @@ -5264,21 +5325,17 @@ class UsageDetailsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[UsageDetail]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[UsageDetail]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(UsageDetailsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_patch.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_patch.py index 0ad201a8c586e..f7dd32510333d 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_patch.py @@ -10,6 +10,7 @@ __all__: List[str] = [] # Add all objects you want publicly available to users at this package level + def patch_sdk(): """Do not remove from this file. diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py index bd4e5bf2cdbd8..33de5eb645bc9 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/__init__.py @@ -25,26 +25,27 @@ from ._credits_operations import CreditsOperations from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'UsageDetailsOperations', - 'MarketplacesOperations', - 'BudgetsOperations', - 'TagsOperations', - 'ChargesOperations', - 'BalancesOperations', - 'ReservationsSummariesOperations', - 'ReservationsDetailsOperations', - 'ReservationRecommendationsOperations', - 'ReservationRecommendationDetailsOperations', - 'ReservationTransactionsOperations', - 'PriceSheetOperations', - 'Operations', - 'AggregatedCostOperations', - 'EventsOperations', - 'LotsOperations', - 'CreditsOperations', + "UsageDetailsOperations", + "MarketplacesOperations", + "BudgetsOperations", + "TagsOperations", + "ChargesOperations", + "BalancesOperations", + "ReservationsSummariesOperations", + "ReservationsDetailsOperations", + "ReservationRecommendationsOperations", + "ReservationRecommendationDetailsOperations", + "ReservationTransactionsOperations", + "PriceSheetOperations", + "Operations", + "AggregatedCostOperations", + "EventsOperations", + "LotsOperations", + "CreditsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py index fdff65d608034..9c2f27dc30735 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,83 +25,80 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_by_management_group_request( - management_group_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any + management_group_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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost", + ) # pylint: disable=line-too-long path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, 'str'), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_for_billing_period_by_management_group_request( - management_group_id: str, - billing_period_name: str, - **kwargs: Any + management_group_id: str, billing_period_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost", + ) # pylint: disable=line-too-long path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, 'str'), - "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, 'str'), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class AggregatedCostOperations: """ @@ -116,18 +119,14 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get_by_management_group( - self, - management_group_id: str, - filter: Optional[str] = None, - **kwargs: Any + self, management_group_id: str, filter: Optional[str] = None, **kwargs: Any ) -> _models.ManagementGroupAggregatedCostResult: """Provides the aggregate cost of a management group and all child management groups by current billing period. - :param management_group_id: Azure Management Group ID. + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str :param filter: May be used to filter aggregated cost by properties/usageStart (Utc time), properties/usageEnd (Utc time). The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It @@ -135,38 +134,41 @@ def get_by_management_group( key and value is separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ManagementGroupAggregatedCostResult, or the result of cls(response) + :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ManagementGroupAggregatedCostResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_by_management_group_request( management_group_id=management_group_id, - api_version=api_version, filter=filter, - template_url=self.get_by_management_group.metadata['url'], + api_version=api_version, + template_url=self.get_by_management_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -174,63 +176,64 @@ def get_by_management_group( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ManagementGroupAggregatedCostResult', pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_management_group.metadata = {'url': "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost"} # type: ignore - + get_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost" + } @distributed_trace def get_for_billing_period_by_management_group( - self, - management_group_id: str, - billing_period_name: str, - **kwargs: Any + self, management_group_id: str, billing_period_name: str, **kwargs: Any ) -> _models.ManagementGroupAggregatedCostResult: """Provides the aggregate cost of a management group and all child management groups by specified billing period. - :param management_group_id: Azure Management Group ID. + :param management_group_id: Azure Management Group ID. Required. :type management_group_id: str - :param billing_period_name: Billing Period Name. + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ManagementGroupAggregatedCostResult, or the result of cls(response) + :return: ManagementGroupAggregatedCostResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ManagementGroupAggregatedCostResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_management_group_request( management_group_id=management_group_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_management_group.metadata['url'], + template_url=self.get_for_billing_period_by_management_group.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -238,12 +241,13 @@ def get_for_billing_period_by_management_group( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ManagementGroupAggregatedCostResult', pipeline_response) + deserialized = self._deserialize("ManagementGroupAggregatedCostResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_for_billing_period_by_management_group.metadata = {'url': "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost"} # type: ignore - + get_for_billing_period_by_management_group.metadata = { + "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py index 2bafa484a16b0..2120804fedc2a 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,79 +25,76 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_by_billing_account_request( - billing_account_id: str, - **kwargs: Any -) -> HttpRequest: + +def build_get_by_billing_account_request(billing_account_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances", + ) # pylint: disable=line-too-long path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, 'str'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_for_billing_period_by_billing_account_request( - billing_account_id: str, - billing_period_name: str, - **kwargs: Any + billing_account_id: str, billing_period_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances", + ) # pylint: disable=line-too-long path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, 'str'), - "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, 'str'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class BalancesOperations: """ @@ -112,50 +115,48 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def get_by_billing_account( - self, - billing_account_id: str, - **kwargs: Any - ) -> _models.Balance: + def get_by_billing_account(self, billing_account_id: str, **kwargs: Any) -> _models.Balance: """Gets the balances for a scope by billingAccountId. Balances are available via this API only for May 1, 2014 or later. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Balance, or the result of cls(response) + :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Balance] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_by_billing_account_request( billing_account_id=billing_account_id, api_version=api_version, - template_url=self.get_by_billing_account.metadata['url'], + template_url=self.get_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -163,63 +164,64 @@ def get_by_billing_account( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Balance', pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances"} # type: ignore - + get_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances" + } @distributed_trace def get_for_billing_period_by_billing_account( - self, - billing_account_id: str, - billing_period_name: str, - **kwargs: Any + self, billing_account_id: str, billing_period_name: str, **kwargs: Any ) -> _models.Balance: """Gets the balances for a scope by billing period and billingAccountId. Balances are available via this API only for May 1, 2014 or later. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_period_name: Billing Period Name. + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Balance, or the result of cls(response) + :return: Balance or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Balance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Balance] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) - request = build_get_for_billing_period_by_billing_account_request( billing_account_id=billing_account_id, billing_period_name=billing_period_name, api_version=api_version, - template_url=self.get_for_billing_period_by_billing_account.metadata['url'], + template_url=self.get_for_billing_period_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -227,12 +229,13 @@ def get_for_billing_period_by_billing_account( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Balance', pipeline_response) + deserialized = self._deserialize("Balance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_for_billing_period_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances"} # type: ignore - + get_for_billing_period_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py index 4aac341b69676..f8731081cab61 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,157 +27,121 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - scope: str, - **kwargs: Any -) -> HttpRequest: + +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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/budgets") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_get_request( - scope: str, - budget_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, budget_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), - "budgetName": _SERIALIZER.url("budget_name", budget_name, 'str'), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "budgetName": _SERIALIZER.url("budget_name", budget_name, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_create_or_update_request( - scope: str, - budget_name: str, - *, - json: Optional[_models.Budget] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: + _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, budget_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), - "budgetName": _SERIALIZER.url("budget_name", budget_name, 'str'), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "budgetName": _SERIALIZER.url("budget_name", budget_name, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="PUT", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request( - scope: str, - budget_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, budget_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), - "budgetName": _SERIALIZER.url("budget_name", budget_name, 'str'), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "budgetName": _SERIALIZER.url("budget_name", budget_name, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class BudgetsOperations: """ @@ -191,13 +162,8 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - scope: str, - **kwargs: Any - ) -> Iterable[_models.BudgetsListResult]: + def list(self, scope: str, **kwargs: Any) -> Iterable["_models.Budget"]: """Lists all budgets for the defined scope. :param scope: The scope associated with budget operations. This includes @@ -213,47 +179,57 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection 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 BudgetsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.BudgetsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Budget or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Budget] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.BudgetsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.BudgetsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( scope=scope, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - scope=scope, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -261,16 +237,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("BudgetsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -281,19 +255,12 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets"} # type: ignore + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets"} @distributed_trace - def get( - self, - scope: str, - budget_name: str, - **kwargs: Any - ) -> _models.Budget: + def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: """Gets the budget for the scope by budget name. :param scope: The scope associated with budget operations. This includes @@ -309,43 +276,46 @@ def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection scope. Required. :type scope: str - :param budget_name: Budget Name. + :param budget_name: Budget Name. Required. :type budget_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Budget, or the result of cls(response) + :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Budget] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) - request = build_get_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -353,22 +323,23 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Budget', pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} - - @distributed_trace + @overload def create_or_update( self, scope: str, budget_name: str, parameters: _models.Budget, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.Budget: """The operation to create or update a budget. You can optionally provide an eTag if desired as a @@ -388,30 +359,117 @@ def create_or_update( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection scope. Required. :type scope: str - :param budget_name: Budget Name. + :param budget_name: Budget Name. Required. :type budget_name: str - :param parameters: Parameters supplied to the Create Budget operation. + :param parameters: Parameters supplied to the Create Budget operation. Required. :type parameters: ~azure.mgmt.consumption.models.Budget + :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: Budget or the result of cls(response) + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, scope: str, budget_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Budget: + """The operation to create or update a budget. You can optionally provide an eTag if desired as a + form of concurrency control. To obtain the latest eTag for a given budget, perform a get + operation prior to your put operation. + + :param scope: The scope associated with budget 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.Management/managementGroups/{managementGroupId}' for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :param parameters: Parameters supplied to the Create Budget 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: Budget or the result of cls(response) + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, scope: str, budget_name: str, parameters: Union[_models.Budget, IO], **kwargs: Any + ) -> _models.Budget: + """The operation to create or update a budget. You can optionally provide an eTag if desired as a + form of concurrency control. To obtain the latest eTag for a given budget, perform a get + operation prior to your put operation. + + :param scope: The scope associated with budget 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.Management/managementGroups/{managementGroupId}' for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :param parameters: Parameters supplied to the Create Budget operation. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.consumption.models.Budget 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: Budget, or the result of cls(response) + :return: Budget or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.Budget - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Budget] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) - _json = self._serialize.body(parameters, 'Budget') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Budget") request = build_create_or_update_request( scope=scope, @@ -419,18 +477,18 @@ def create_or_update( api_version=api_version, content_type=content_type, json=_json, - template_url=self.create_or_update.metadata['url'], + 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 + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: @@ -439,25 +497,21 @@ def create_or_update( raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Budget', pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Budget', pipeline_response) + deserialized = self._deserialize("Budget", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - create_or_update.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} # type: ignore + return deserialized # type: ignore + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} @distributed_trace def delete( # pylint: disable=inconsistent-return-statements - self, - scope: str, - budget_name: str, - **kwargs: Any + self, scope: str, budget_name: str, **kwargs: Any ) -> None: """The operation to delete a budget. @@ -474,43 +528,46 @@ def delete( # pylint: disable=inconsistent-return-statements '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for billingProfile scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope. + for invoiceSection scope. Required. :type scope: str - :param budget_name: Budget Name. + :param budget_name: Budget Name. Required. :type budget_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: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( scope=scope, budget_name=budget_name, api_version=api_version, - template_url=self.delete.metadata['url'], + template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -521,5 +578,4 @@ def delete( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} # type: ignore - + delete.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py index a1edc4a38ba71..e471dfe960285 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,13 +25,20 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( scope: str, *, @@ -38,38 +51,33 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/charges") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if start_date is not None: - _params['startDate'] = _SERIALIZER.query("start_date", start_date, 'str') + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") if end_date is not None: - _params['endDate'] = _SERIALIZER.query("end_date", end_date, 'str') + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if apply is not None: - _params['$apply'] = _SERIALIZER.query("apply", apply, 'str') + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ChargesOperations: """ @@ -90,7 +98,6 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( self, @@ -118,7 +125,7 @@ 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 start_date: Start date. Default value is None. :type start_date: str @@ -135,41 +142,44 @@ def list( None. :type apply: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChargesListResult, or the result of cls(response) + :return: ChargesListResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ChargesListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ChargesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ChargesListResult] = kwargs.pop("cls", None) - request = build_list_request( scope=scope, - api_version=api_version, start_date=start_date, end_date=end_date, filter=filter, apply=apply, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -177,12 +187,11 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ChargesListResult', pipeline_response) + deserialized = self._deserialize("ChargesListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/charges"} # type: ignore - + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/charges"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py index c039d76168a52..530dbf701b325 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,46 +25,47 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - billing_account_id: str, - billing_profile_id: str, - **kwargs: Any -) -> HttpRequest: + +def build_get_request(billing_account_id: str, billing_profile_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary", + ) # 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'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class CreditsOperations: """ @@ -79,53 +86,50 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def get( - self, - billing_account_id: str, - billing_profile_id: str, - **kwargs: Any - ) -> Optional[_models.CreditSummary]: + def get(self, billing_account_id: str, billing_profile_id: str, **kwargs: Any) -> Optional[_models.CreditSummary]: """The credit summary by billingAccountId and billingProfileId. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CreditSummary, or the result of cls(response) + :return: CreditSummary or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.CreditSummary or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.CreditSummary]] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[Optional[_models.CreditSummary]] = kwargs.pop("cls", None) - request = build_get_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -135,12 +139,13 @@ def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('CreditSummary', pipeline_response) + deserialized = self._deserialize("CreditSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary"} # type: ignore - + get.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py index 3a1d4c6dade9c..a9f78867dcfb3 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,88 +27,82 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_billing_profile_request( - billing_account_id: str, - billing_profile_id: str, - *, - start_date: str, - end_date: str, - **kwargs: Any + 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 {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events", + ) # 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'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') - _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") + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request( - billing_account_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any + billing_account_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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events", + ) # pylint: disable=line-too-long path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, 'str'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class EventsOperations: """ @@ -122,72 +123,73 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_billing_profile( - self, - billing_account_id: str, - billing_profile_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> Iterable[_models.Events]: + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Iterable["_models.EventSummary"]: """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile 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 - :return: An iterator like instance of either Events or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Events] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EventSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.EventSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Events] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Events] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, - api_version=api_version, start_date=start_date, end_date=end_date, - template_url=self.list_by_billing_profile.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_profile_request( - billing_account_id=billing_account_id, - billing_profile_id=billing_profile_id, - api_version=api_version, - start_date=start_date, - end_date=end_date, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -195,16 +197,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -215,23 +215,20 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events"} # type: ignore + list_by_billing_profile.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events" + } @distributed_trace def list_by_billing_account( - self, - billing_account_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable[_models.Events]: + self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.EventSummary"]: """Lists the events that decrements Azure credits or Microsoft Azure consumption commitment for a billing account or a billing profile for a given start and end date. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the events by lotId, lotSource etc. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. @@ -239,46 +236,55 @@ def list_by_billing_account( value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Events or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Events] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EventSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.EventSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Events] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Events] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_account_request( billing_account_id=billing_account_id, - api_version=api_version, filter=filter, - template_url=self.list_by_billing_account.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_account_request( - billing_account_id=billing_account_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -286,16 +292,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("Events", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -306,8 +310,8 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events"} # type: ignore + list_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py index dea6a3b24baab..cd94ed0583b99 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,122 +27,112 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_billing_profile_request( - billing_account_id: str, - billing_profile_id: str, - **kwargs: Any + billing_account_id: str, billing_profile_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots", + ) # 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'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_account_request( - billing_account_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any + billing_account_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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots", + ) # pylint: disable=line-too-long path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, 'str'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_customer_request( - billing_account_id: str, - customer_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any + billing_account_id: str, customer_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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots", + ) # pylint: disable=line-too-long path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, 'str'), - "customerId": _SERIALIZER.url("customer_id", customer_id, 'str'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class LotsOperations: """ @@ -156,62 +153,67 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_billing_profile( - self, - billing_account_id: str, - billing_profile_id: str, - **kwargs: Any - ) -> Iterable[_models.Lots]: + self, billing_account_id: str, billing_profile_id: str, **kwargs: Any + ) -> Iterable["_models.LotSummary"]: """Lists all Azure credits for a billing account or a billing profile. The API is only supported for Microsoft Customer Agreements (MCA) billing accounts. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Lots or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Lots] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LotSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Lots] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Lots] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, api_version=api_version, - template_url=self.list_by_billing_profile.metadata['url'], + template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_profile_request( - billing_account_id=billing_account_id, - billing_profile_id=billing_profile_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -219,16 +221,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -239,24 +239,21 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots"} # type: ignore + list_by_billing_profile.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots" + } @distributed_trace def list_by_billing_account( - self, - billing_account_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable[_models.Lots]: + self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.LotSummary"]: """Lists all Microsoft Azure consumption commitments for a billing account. The API is only supported for Microsoft Customer Agreements (MCA) and Direct Enterprise Agreement (EA) billing accounts. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: May be used to filter the lots by Status, Source etc. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag @@ -264,46 +261,55 @@ def list_by_billing_account( value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Lots or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Lots] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LotSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Lots] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Lots] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_account_request( billing_account_id=billing_account_id, - api_version=api_version, filter=filter, - template_url=self.list_by_billing_account.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_account_request( - billing_account_id=billing_account_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -311,16 +317,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -331,74 +335,78 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots"} # type: ignore + list_by_billing_account.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots" + } @distributed_trace def list_by_customer( - self, - billing_account_id: str, - customer_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable[_models.Lots]: + self, billing_account_id: str, customer_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.LotSummary"]: """Lists all Azure credits for a customer. The API is only supported for Microsoft Partner Agreements (MPA) billing accounts. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param customer_id: Customer ID. + :param customer_id: Customer ID. Required. :type customer_id: str :param filter: May be used to filter the lots by Status, Source etc. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. Tag filter is a key value pair string where key and value is separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Lots or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Lots] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LotSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Lots] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.Lots] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_customer_request( billing_account_id=billing_account_id, customer_id=customer_id, - api_version=api_version, filter=filter, - template_url=self.list_by_customer.metadata['url'], + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_customer_request( - billing_account_id=billing_account_id, - customer_id=customer_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -406,16 +414,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("Lots", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -426,8 +432,8 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots"} # type: ignore + list_by_customer.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py index 8a1e56307e4f5..36cc085b75d98 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,13 +27,20 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( scope: str, *, @@ -38,36 +52,31 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/marketplaces") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if top is not None: - _params['$top'] = _SERIALIZER.query("top", top, 'int', maximum=1000, minimum=1) + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) if skiptoken is not None: - _params['$skiptoken'] = _SERIALIZER.query("skiptoken", skiptoken, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class MarketplacesOperations: """ @@ -88,7 +97,6 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( self, @@ -97,7 +105,7 @@ def list( top: Optional[int] = None, skiptoken: Optional[str] = None, **kwargs: Any - ) -> Iterable[_models.MarketplacesListResult]: + ) -> Iterable["_models.Marketplace"]: """Lists the marketplaces for a scope at the defined scope. Marketplaces are available via this API only for May 1, 2014 or later. @@ -112,6 +120,7 @@ def list( '/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. For e.g. to specify billing period at department scope use '/providers/Microsoft.Billing/departments/{departmentId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. + Required. :type scope: str :param filter: May be used to filter marketplaces by properties/usageEnd (Utc time), properties/usageStart (Utc time), properties/resourceGroup, properties/instanceName or @@ -127,51 +136,57 @@ def list( value is None. :type skiptoken: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either MarketplacesListResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.MarketplacesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Marketplace or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Marketplace] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.MarketplacesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.MarketplacesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( scope=scope, - api_version=api_version, filter=filter, top=top, skiptoken=skiptoken, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - scope=scope, - api_version=api_version, - filter=filter, - top=top, - skiptoken=skiptoken, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -179,28 +194,24 @@ def extract_data(pipeline_response): deserialized = self._deserialize("MarketplacesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + 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, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/marketplaces"} # type: ignore + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/marketplaces"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py index b378ce12ee4d5..5dd6eb4d602ca 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,38 +27,38 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: + +def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.Consumption/operations") # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class Operations: """ @@ -72,51 +79,58 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable[_models.OperationListResult]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available consumption 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.consumption.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.consumption.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.OperationListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -124,16 +138,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -144,8 +156,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.Consumption/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.Consumption/operations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_patch.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_patch.py index 0ad201a8c586e..f7dd32510333d 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_patch.py @@ -10,6 +10,7 @@ __all__: List[str] = [] # Add all objects you want publicly available to users at this package level + def patch_sdk(): """Do not remove from this file. diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py index 91f29f6db54a6..971a668213341 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,13 +25,20 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( subscription_id: str, *, @@ -37,41 +50,37 @@ def build_get_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default") + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default" + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if expand is not None: - _params['$expand'] = _SERIALIZER.query("expand", expand, 'str') + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") if skiptoken is not None: - _params['$skiptoken'] = _SERIALIZER.query("skiptoken", skiptoken, 'str') + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") if top is not None: - _params['$top'] = _SERIALIZER.query("top", top, 'int', maximum=1000, minimum=1) - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_by_billing_period_request( - subscription_id: str, billing_period_name: str, + subscription_id: str, *, expand: Optional[str] = None, skiptoken: Optional[str] = None, @@ -81,37 +90,35 @@ def build_get_by_billing_period_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if expand is not None: - _params['$expand'] = _SERIALIZER.query("expand", expand, 'str') + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") if skiptoken is not None: - _params['$skiptoken'] = _SERIALIZER.query("skiptoken", skiptoken, 'str') + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") if top is not None: - _params['$top'] = _SERIALIZER.query("top", top, 'int', maximum=1000, minimum=1) - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + class PriceSheetOperations: """ @@ -132,14 +139,9 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( - self, - expand: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any + self, expand: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any ) -> _models.PriceSheetResult: """Gets the price sheet for a subscription. Price sheet is available via this API only for May 1, 2014 or later. @@ -156,40 +158,43 @@ def get( None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: PriceSheetResult, or the result of cls(response) + :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PriceSheetResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_request( subscription_id=self._config.subscription_id, - api_version=api_version, expand=expand, skiptoken=skiptoken, top=top, - template_url=self.get.metadata['url'], + api_version=api_version, + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -197,15 +202,14 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PriceSheetResult', pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} @distributed_trace def get_by_billing_period( @@ -219,7 +223,7 @@ def get_by_billing_period( """Get the price sheet for a scope by subscriptionId and billing period. Price sheet is available via this API only for May 1, 2014 or later. - :param billing_period_name: Billing Period Name. + :param billing_period_name: Billing Period Name. Required. :type billing_period_name: str :param expand: May be used to expand the properties/meterDetails within a price sheet. By default, these fields are not included when returning price sheet. Default value is None. @@ -233,41 +237,44 @@ def get_by_billing_period( None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: PriceSheetResult, or the result of cls(response) + :return: PriceSheetResult or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PriceSheetResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) - request = build_get_by_billing_period_request( - subscription_id=self._config.subscription_id, billing_period_name=billing_period_name, - api_version=api_version, + subscription_id=self._config.subscription_id, expand=expand, skiptoken=skiptoken, top=top, - template_url=self.get_by_billing_period.metadata['url'], + api_version=api_version, + template_url=self.get_by_billing_period.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -275,12 +282,13 @@ def get_by_billing_period( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PriceSheetResult', pipeline_response) + deserialized = self._deserialize("PriceSheetResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_period.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default"} # type: ignore - + get_by_billing_period.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py index f972674365edc..7e44d960f0782 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar, Union -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,55 +25,59 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( resource_scope: str, *, - scope: Union[str, "_models.Scope"], + scope: Union[str, _models.Scope], region: str, - term: Union[str, "_models.Term"], - look_back_period: Union[str, "_models.LookBackPeriod"], + term: Union[str, _models.Term], + look_back_period: Union[str, _models.LookBackPeriod], product: 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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails") + _url = kwargs.pop( + "template_url", "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails" + ) path_format_arguments = { - "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, 'str', skip_quote=True), + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') - _params['scope'] = _SERIALIZER.query("scope", scope, 'str') - _params['region'] = _SERIALIZER.query("region", region, 'str') - _params['term'] = _SERIALIZER.query("term", term, 'str') - _params['lookBackPeriod'] = _SERIALIZER.query("look_back_period", look_back_period, 'str') - _params['product'] = _SERIALIZER.query("product", product, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["scope"] = _SERIALIZER.query("scope", scope, "str") + _params["region"] = _SERIALIZER.query("region", region, "str") + _params["term"] = _SERIALIZER.query("term", term, "str") + _params["lookBackPeriod"] = _SERIALIZER.query("look_back_period", look_back_period, "str") + _params["product"] = _SERIALIZER.query("product", product, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + class ReservationRecommendationDetailsOperations: """ @@ -88,15 +98,14 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( self, resource_scope: str, - scope: Union[str, "_models.Scope"], + scope: Union[str, _models.Scope], region: str, - term: Union[str, "_models.Term"], - look_back_period: Union[str, "_models.LookBackPeriod"], + term: Union[str, _models.Term], + look_back_period: Union[str, _models.LookBackPeriod], product: str, **kwargs: Any ) -> Optional[_models.ReservationRecommendationDetailsModel]: @@ -107,57 +116,62 @@ def get( '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope. + for billingProfile scope. Required. :type resource_scope: str - :param scope: Scope of the reservation. + :param scope: Scope of the reservation. Known values are: "Single" and "Shared". Required. :type scope: str or ~azure.mgmt.consumption.models.Scope - :param region: Used to select the region the recommendation should be generated for. + :param region: Used to select the region the recommendation should be generated for. Required. :type region: str - :param term: Specify length of reservation recommendation term. + :param term: Specify length of reservation recommendation term. Known values are: "P1Y" and + "P3Y". Required. :type term: str or ~azure.mgmt.consumption.models.Term :param look_back_period: Filter the time period on which reservation recommendation results are - based. + based. Known values are: "Last7Days", "Last30Days", and "Last60Days". Required. :type look_back_period: str or ~azure.mgmt.consumption.models.LookBackPeriod :param product: Filter the products for which reservation recommendation results are generated. Examples: Standard_DS1_v2 (for VM), Premium_SSD_Managed_Disks_P30 (for Managed Disks). + Required. :type product: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationRecommendationDetailsModel, or the result of cls(response) + :return: ReservationRecommendationDetailsModel or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] = kwargs.pop("cls", None) - request = build_get_request( resource_scope=resource_scope, - api_version=api_version, scope=scope, region=region, term=term, look_back_period=look_back_period, product=product, - template_url=self.get.metadata['url'], + api_version=api_version, + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -167,12 +181,11 @@ def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ReservationRecommendationDetailsModel', pipeline_response) + deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails"} # type: ignore - + get.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py index c22694438f394..5f8707a5a5af2 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,48 +27,45 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - resource_scope: str, - *, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: + +def build_list_request(resource_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 {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations") path_format_arguments = { - "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, 'str', skip_quote=True), + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ReservationRecommendationsOperations: """ @@ -82,14 +86,10 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( - self, - resource_scope: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable[_models.ReservationRecommendationsListResult]: + self, resource_scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ReservationRecommendation"]: """List of recommendations for purchasing reserved instances. :param resource_scope: The scope associated with reservation recommendations operations. This @@ -97,7 +97,7 @@ def list( '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope. + for billingProfile scope. Required. :type resource_scope: str :param filter: May be used to filter reservationRecommendations by: properties/scope with allowed values ['Single', 'Shared'] and default value 'Single'; properties/resourceType with @@ -108,48 +108,56 @@ def list( default value 'Last7Days'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationRecommendationsListResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationRecommendationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationRecommendation or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationRecommendation] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationRecommendationsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationRecommendationsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( resource_scope=resource_scope, - api_version=api_version, filter=filter, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - resource_scope=resource_scope, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -157,16 +165,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationRecommendationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -177,8 +183,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations"} # type: ignore + list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py index 2d58f28caf773..ec45824673748 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,87 +27,80 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - billing_account_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: + +def build_list_request(billing_account_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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions", + ) # pylint: disable=line-too-long path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, 'str'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_billing_profile_request( - billing_account_id: str, - billing_profile_id: str, - *, - filter: Optional[str] = None, - **kwargs: Any + billing_account_id: str, billing_profile_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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions", + ) # 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'), + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ReservationTransactionsOperations: """ @@ -121,64 +121,76 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( - self, - billing_account_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable[_models.ReservationTransactionsListResult]: - """List of transactions for reserved instances on billing account scope. - - :param billing_account_id: BillingAccount ID. + self, billing_account_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ReservationTransaction"]: + """List of transactions for reserved instances on billing account scope. Note: The refund + transactions are posted along with its purchase transaction (i.e. in the purchase billing + month). For example, The refund is requested in May 2021. This refund transaction will have + event date as May 2021 but the billing month as April 2020 when the reservation purchase was + made. + + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str :param filter: Filter reservation transactions by date range. The properties/EventDate for - start date and end date. The filter supports 'le' and 'ge'. Default value is None. + start date and end date. The filter supports 'le' and 'ge'. Note: API returns data for the + entire start date's and end date's billing month. For example, filter + properties/eventDate+ge+2020-01-01+AND+properties/eventDate+le+2020-12-29 will include data for + the entire December 2020 month (i.e. will contain records for dates December 30 and 31). + Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationTransactionsListResult or the result of + :return: An iterator like instance of either ReservationTransaction or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationTransactionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationTransactionsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationTransactionsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( billing_account_id=billing_account_id, - api_version=api_version, filter=filter, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - billing_account_id=billing_account_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -186,16 +198,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationTransactionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -206,74 +216,85 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions"} # type: ignore + list.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions" + } @distributed_trace def list_by_billing_profile( - self, - billing_account_id: str, - billing_profile_id: str, - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable[_models.ModernReservationTransactionsListResult]: - """List of transactions for reserved instances on billing account scope. - - :param billing_account_id: BillingAccount ID. + self, billing_account_id: str, billing_profile_id: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ModernReservationTransaction"]: + """List of transactions for reserved instances on billing profile scope. The refund transactions + are posted along with its purchase transaction (i.e. in the purchase billing month). For + example, The refund is requested in May 2021. This refund transaction will have event date as + May 2021 but the billing month as April 2020 when the reservation purchase was made. + + :param billing_account_id: BillingAccount ID. Required. :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. + :param billing_profile_id: Azure Billing Profile ID. Required. :type billing_profile_id: str :param filter: Filter reservation transactions by date range. The properties/EventDate for - start date and end date. The filter supports 'le' and 'ge'. Default value is None. + start date and end date. The filter supports 'le' and 'ge'. Note: API returns data for the + entire start date's and end date's billing month. For example, filter + properties/eventDate+ge+2020-01-01+AND+properties/eventDate+le+2020-12-29 will include data for + entire December 2020 month (i.e. will contain records for dates December 30 and 31). Default + value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ModernReservationTransactionsListResult or the - result of cls(response) + :return: An iterator like instance of either ModernReservationTransaction or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ModernReservationTransactionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ModernReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ModernReservationTransactionsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ModernReservationTransactionsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_billing_profile_request( billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, - api_version=api_version, filter=filter, - template_url=self.list_by_billing_profile.metadata['url'], + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_billing_profile_request( - billing_account_id=billing_account_id, - billing_profile_id=billing_profile_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -281,16 +302,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ModernReservationTransactionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -301,8 +320,8 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions"} # type: ignore + list_by_billing_profile.metadata = { + "url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions" + } diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py index 0d72a1aeb1762..f4fb832761108 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,85 +27,77 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_by_reservation_order_request( - reservation_order_id: str, - *, - filter: str, - **kwargs: Any -) -> HttpRequest: + +def build_list_by_reservation_order_request(reservation_order_id: str, *, filter: 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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_reservation_order_and_reservation_request( - reservation_order_id: str, - reservation_id: str, - *, - filter: str, - **kwargs: Any + reservation_order_id: str, reservation_id: str, *, filter: 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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( @@ -114,40 +113,35 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails") path_format_arguments = { - "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, 'str', skip_quote=True), + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if start_date is not None: - _params['startDate'] = _SERIALIZER.query("start_date", start_date, 'str') + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") if end_date is not None: - _params['endDate'] = _SERIALIZER.query("end_date", end_date, 'str') + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if reservation_id is not None: - _params['reservationId'] = _SERIALIZER.query("reservation_id", reservation_id, 'str') + _params["reservationId"] = _SERIALIZER.query("reservation_id", reservation_id, "str") if reservation_order_id is not None: - _params['reservationOrderId'] = _SERIALIZER.query("reservation_order_id", reservation_order_id, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["reservationOrderId"] = _SERIALIZER.query("reservation_order_id", reservation_order_id, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ReservationsDetailsOperations: """ @@ -168,64 +162,69 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_reservation_order( - self, - reservation_order_id: str, - filter: str, - **kwargs: Any - ) -> Iterable[_models.ReservationDetailsListResult]: - """Lists the reservations details for provided date range. + self, reservation_order_id: str, filter: str, **kwargs: Any + ) -> Iterable["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, + API call should be made with smaller date ranges. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str :param filter: Filter reservation details by date range. The properties/UsageDate for start - date and end date. The filter supports 'le' and 'ge'. + date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationDetailsListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationDetail or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, - api_version=api_version, filter=filter, - template_url=self.list_by_reservation_order.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -233,16 +232,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -253,74 +250,78 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_reservation_order.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails"} # type: ignore + list_by_reservation_order.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails" + } @distributed_trace def list_by_reservation_order_and_reservation( - self, - reservation_order_id: str, - reservation_id: str, - filter: str, - **kwargs: Any - ) -> Iterable[_models.ReservationDetailsListResult]: - """Lists the reservations details for provided date range. + self, reservation_order_id: str, reservation_id: str, filter: str, **kwargs: Any + ) -> Iterable["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 502 when the response size exceeds the ARM limit. In such cases, + API call should be made with smaller date ranges. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the reservation. + :param reservation_id: Id of the reservation. Required. :type reservation_id: str :param filter: Filter reservation details by date range. The properties/UsageDate for start - date and end date. The filter supports 'le' and 'ge'. + date and end date. The filter supports 'le' and 'ge'. Required. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationDetailsListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationDetail or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, - api_version=api_version, filter=filter, - template_url=self.list_by_reservation_order_and_reservation.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_and_reservation_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -328,16 +329,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -348,11 +347,11 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_reservation_order_and_reservation.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails"} # type: ignore + list_by_reservation_order_and_reservation.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails" + } @distributed_trace def list( @@ -364,14 +363,16 @@ def list( reservation_id: Optional[str] = None, reservation_order_id: Optional[str] = None, **kwargs: Any - ) -> Iterable[_models.ReservationDetailsListResult]: - """Lists the reservations details for the defined scope and provided date range. + ) -> Iterable["_models.ReservationDetail"]: + """Lists the reservations details for the defined scope and provided date range. Note: ARM has a + payload size limit of 12MB, so currently callers get 502 when the response size exceeds the ARM + limit. In such cases, API call should be made with smaller date ranges. :param resource_scope: The scope associated with reservations details operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope (legacy), and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for BillingProfile scope (modern). + for BillingProfile scope (modern). Required. :type resource_scope: str :param start_date: Start date. Only applicable when querying with billing profile. Default value is None. @@ -390,56 +391,59 @@ def list( Filter to a specific reservation order. Default value is None. :type reservation_order_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationDetailsListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationDetail or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( resource_scope=resource_scope, - api_version=api_version, start_date=start_date, end_date=end_date, filter=filter, reservation_id=reservation_id, reservation_order_id=reservation_order_id, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - resource_scope=resource_scope, - api_version=api_version, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -447,16 +451,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -467,8 +469,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails"} # type: ignore + list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py index 939d81eb28e0f..d76164bcc81e1 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,97 +27,94 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_reservation_order_request( - reservation_order_id: str, - *, - grain: Union[str, "_models.Datagrain"], - filter: Optional[str] = None, - **kwargs: Any + reservation_order_id: str, *, grain: Union[str, _models.Datagrain], 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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['grain'] = _SERIALIZER.query("grain", grain, 'str') + _params["grain"] = _SERIALIZER.query("grain", grain, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_reservation_order_and_reservation_request( reservation_order_id: str, reservation_id: str, *, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], 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 - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries", + ) # pylint: disable=line-too-long path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, 'str'), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, 'str'), + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['grain'] = _SERIALIZER.query("grain", grain, 'str') + _params["grain"] = _SERIALIZER.query("grain", grain, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_request( resource_scope: str, *, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], start_date: Optional[str] = None, end_date: Optional[str] = None, filter: Optional[str] = None, @@ -121,41 +125,36 @@ def build_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries") path_format_arguments = { - "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, 'str', skip_quote=True), + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['grain'] = _SERIALIZER.query("grain", grain, 'str') + _params["grain"] = _SERIALIZER.query("grain", grain, "str") if start_date is not None: - _params['startDate'] = _SERIALIZER.query("start_date", start_date, 'str') + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") if end_date is not None: - _params['endDate'] = _SERIALIZER.query("end_date", end_date, 'str') + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if reservation_id is not None: - _params['reservationId'] = _SERIALIZER.query("reservation_id", reservation_id, 'str') + _params["reservationId"] = _SERIALIZER.query("reservation_id", reservation_id, "str") if reservation_order_id is not None: - _params['reservationOrderId'] = _SERIALIZER.query("reservation_order_id", reservation_order_id, 'str') - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["reservationOrderId"] = _SERIALIZER.query("reservation_order_id", reservation_order_id, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ReservationsSummariesOperations: """ @@ -176,69 +175,74 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_reservation_order( self, reservation_order_id: str, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], filter: Optional[str] = None, **kwargs: Any - ) -> Iterable[_models.ReservationSummariesListResult]: + ) -> Iterable["_models.ReservationSummary"]: """Lists the reservations summaries for daily or monthly grain. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param grain: Can be daily or monthly. + :param grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. :type grain: str or ~azure.mgmt.consumption.models.Datagrain :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationSummariesListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummariesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationSummariesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_request( reservation_order_id=reservation_order_id, - api_version=api_version, grain=grain, filter=filter, - template_url=self.list_by_reservation_order.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - grain=grain, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -246,16 +250,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -266,79 +268,84 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_reservation_order.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries"} # type: ignore + list_by_reservation_order.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries" + } @distributed_trace def list_by_reservation_order_and_reservation( self, reservation_order_id: str, reservation_id: str, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], filter: Optional[str] = None, **kwargs: Any - ) -> Iterable[_models.ReservationSummariesListResult]: + ) -> Iterable["_models.ReservationSummary"]: """Lists the reservations summaries for daily or monthly grain. - :param reservation_order_id: Order Id of the reservation. + :param reservation_order_id: Order Id of the reservation. Required. :type reservation_order_id: str - :param reservation_id: Id of the reservation. + :param reservation_id: Id of the reservation. Required. :type reservation_id: str - :param grain: Can be daily or monthly. + :param grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. :type grain: str or ~azure.mgmt.consumption.models.Datagrain :param filter: Required only for daily grain. The properties/UsageDate for start date and end date. The filter supports 'le' and 'ge'. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationSummariesListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummariesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationSummariesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_reservation_order_and_reservation_request( reservation_order_id=reservation_order_id, reservation_id=reservation_id, - api_version=api_version, grain=grain, filter=filter, - template_url=self.list_by_reservation_order_and_reservation.metadata['url'], + api_version=api_version, + template_url=self.list_by_reservation_order_and_reservation.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_by_reservation_order_and_reservation_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - grain=grain, - filter=filter, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -346,16 +353,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -366,33 +371,33 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_reservation_order_and_reservation.metadata = {'url': "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries"} # type: ignore + list_by_reservation_order_and_reservation.metadata = { + "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries" + } @distributed_trace def list( self, resource_scope: str, - grain: Union[str, "_models.Datagrain"], + grain: Union[str, _models.Datagrain], start_date: Optional[str] = None, end_date: Optional[str] = None, filter: Optional[str] = None, reservation_id: Optional[str] = None, reservation_order_id: Optional[str] = None, **kwargs: Any - ) -> Iterable[_models.ReservationSummariesListResult]: + ) -> Iterable["_models.ReservationSummary"]: """Lists the reservations summaries for the defined scope daily or monthly grain. :param resource_scope: The scope associated with reservations summaries operations. This includes '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope (legacy), and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for BillingProfile scope (modern). + for BillingProfile scope (modern). Required. :type resource_scope: str - :param grain: Can be daily or monthly. + :param grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. :type grain: str or ~azure.mgmt.consumption.models.Datagrain :param start_date: Start date. Only applicable when querying with billing profile. Default value is None. @@ -411,58 +416,60 @@ def list( Filter to a specific reservation order. Default value is None. :type reservation_order_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationSummariesListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummariesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ReservationSummary or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ReservationSummariesListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.ReservationSummariesListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( resource_scope=resource_scope, - api_version=api_version, grain=grain, start_date=start_date, end_date=end_date, filter=filter, reservation_id=reservation_id, reservation_order_id=reservation_order_id, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - resource_scope=resource_scope, - api_version=api_version, - grain=grain, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -470,16 +477,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("ReservationSummariesListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -490,8 +495,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries"} # type: ignore + list.metadata = {"url": "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py index d7c429af321dd..cef15e36ba0c7 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,44 +25,43 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - scope: str, - **kwargs: Any -) -> HttpRequest: + +def build_get_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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/tags") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class TagsOperations: """ @@ -77,13 +82,8 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def get( - self, - scope: str, - **kwargs: Any - ) -> Optional[_models.TagsResult]: + def get(self, scope: str, **kwargs: Any) -> Optional[_models.TagsResult]: """Get all available tag keys for the defined scope. :param scope: The scope associated with tags operations. This includes @@ -95,40 +95,43 @@ def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount scope and '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group - scope.. + scope.. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: TagsResult, or the result of cls(response) + :return: TagsResult or None or the result of cls(response) :rtype: ~azure.mgmt.consumption.models.TagsResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.TagsResult]] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[Optional[_models.TagsResult]] = kwargs.pop("cls", None) - request = build_get_request( scope=scope, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: @@ -138,12 +141,11 @@ def get( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('TagsResult', pipeline_response) + deserialized = self._deserialize("TagsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/tags"} # type: ignore - + get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/tags"} diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py index 9e4047ae7c1fe..687fc9e042615 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py @@ -6,11 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,13 +27,20 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( scope: str, *, @@ -34,46 +48,41 @@ def build_list_request( filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, - metric: Optional[Union[str, "_models.Metrictype"]] = None, + metric: Optional[Union[str, _models.Metrictype]] = 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") + api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.Consumption/usageDetails") path_format_arguments = { - "scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters if expand is not None: - _params['$expand'] = _SERIALIZER.query("expand", expand, 'str') + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") if filter is not None: - _params['$filter'] = _SERIALIZER.query("filter", filter, 'str') + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") if skiptoken is not None: - _params['$skiptoken'] = _SERIALIZER.query("skiptoken", skiptoken, 'str') + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") if top is not None: - _params['$top'] = _SERIALIZER.query("top", top, 'int', maximum=1000, minimum=1) - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if metric is not None: - _params['metric'] = _SERIALIZER.query("metric", metric, 'str') + _params["metric"] = _SERIALIZER.query("metric", metric, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class UsageDetailsOperations: """ @@ -94,7 +103,6 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( self, @@ -103,9 +111,9 @@ def list( filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, - metric: Optional[Union[str, "_models.Metrictype"]] = None, + metric: Optional[Union[str, _models.Metrictype]] = None, **kwargs: Any - ) -> Iterable[_models.UsageDetailsListResult]: + ) -> Iterable["_models.UsageDetail"]: """Lists the usage details for the defined scope. Usage details are available via this API only for May 1, 2014 or later. @@ -127,7 +135,7 @@ 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/additionalInfo or properties/meterDetails within a list of usage details. By default, these fields are not included when listing usage @@ -149,58 +157,63 @@ def list( :param top: May be used to limit the number of results to the most recent N usageDetails. Default value is None. :type top: int - :param metric: Allows to select different type of cost/usage records. Default value is None. + :param metric: Allows to select different type of cost/usage records. Known values are: + "actualcost", "amortizedcost", and "usage". Default value is None. :type metric: str or ~azure.mgmt.consumption.models.Metrictype :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either UsageDetailsListResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.UsageDetailsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either UsageDetail or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.UsageDetail] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-10-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.UsageDetailsListResult] + api_version: Literal["2021-10-01"] = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) + cls: ClsType[_models.UsageDetailsListResult] = kwargs.pop("cls", None) error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( scope=scope, - api_version=api_version, expand=expand, filter=filter, skiptoken=skiptoken, top=top, metric=metric, - template_url=self.list.metadata['url'], + api_version=api_version, + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) else: - - request = build_list_request( - scope=scope, - api_version=api_version, - expand=expand, - filter=filter, - skiptoken=skiptoken, - top=top, - metric=metric, - template_url=next_link, - headers=_headers, - params=_params, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + request.url = self._client.format_url(request.url) request.method = "GET" return request @@ -208,16 +221,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("UsageDetailsListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore 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( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -228,8 +239,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/{scope}/providers/Microsoft.Consumption/usageDetails"} # type: ignore + list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/usageDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py new file mode 100644 index 0000000000000..3620ba0642330 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python aggregated_cost_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.aggregated_cost.get_by_management_group( + management_group_id="managementGroupForTest", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py new file mode 100644 index 0000000000000..35594a0f8f157 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_by_management_group_filter_by_date.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python aggregated_cost_by_management_group_filter_by_date.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.aggregated_cost.get_by_management_group( + management_group_id="managementGroupForTest", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostByManagementGroupFilterByDate.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py new file mode 100644 index 0000000000000..03f35dd50ae32 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/aggregated_cost_for_billing_period_by_management_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python aggregated_cost_for_billing_period_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.aggregated_cost.get_for_billing_period_by_management_group( + management_group_id="managementGroupForTest", + billing_period_name="201807", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostForBillingPeriodByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py new file mode 100644 index 0000000000000..cb29ed39ea588 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python balances_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.balances.get_by_billing_account( + billing_account_id="123456", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BalancesByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py new file mode 100644 index 0000000000000..149d33469f554 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/balances_by_billing_account_for_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python balances_by_billing_account_for_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.balances.get_for_billing_period_by_billing_account( + billing_account_id="123456", + billing_period_name="201702", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BalancesByBillingAccountForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py new file mode 100644 index 0000000000000..3d72c42e5a071 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python budget.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.budgets.get( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + budget_name="TestBudget", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/Budget.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py new file mode 100644 index 0000000000000..a07166094b714 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python budgets_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.budgets.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BudgetsList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py new file mode 100644 index 0000000000000..2ce887e2d9f9a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_department.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_for_billing_period_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234/departments/42425", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesForBillingPeriodByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py new file mode 100644 index 0000000000000..c91466879da13 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_for_billing_period_by_enrollment_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_for_billing_period_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234/enrollmentAccounts/42425", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesForBillingPeriodByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py new file mode 100644 index 0000000000000..c48bb008f4ac1 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/billingAccounts/1234:56789", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py new file mode 100644 index 0000000000000..efd41b7b098a3 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_billing_profile_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_billing_account_group_by_billing_profile_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/billingAccounts/1234:56789", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByBillingProfileId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py new file mode 100644 index 0000000000000..04b0cbddbc9fc --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_customer_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_billing_account_group_by_customer_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/billingAccounts/1234:56789", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByCustomerId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py new file mode 100644 index 0000000000000..7035f89b70167 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_account_group_by_invoice_section_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_billing_account_group_by_invoice_section_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/billingAccounts/1234:56789/billingProfiles/42425", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByInvoiceSectionId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py new file mode 100644 index 0000000000000..067b57bb7844a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234:56789/billingProfiles/2460", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py new file mode 100644 index 0000000000000..1ae82b37718a0 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_group_by_invoice_section_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_billing_profile_group_by_invoice_section_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/billingAccounts/1234:56789/billingProfiles/42425", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfileGroupByInvoiceSectionId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py new file mode 100644 index 0000000000000..613175dbc5a04 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_billing_profile_invoice_section.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_billing_profile_invoice_section.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/billingAccounts/1234:56789/billingProfiles/42425/invoiceSections/67890", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfileInvoiceSection.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py new file mode 100644 index 0000000000000..43c9070e4881f --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_customer.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_customer.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234:56789/customers/67890", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernCustomer.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py new file mode 100644 index 0000000000000..2a373da5182be --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_by_modern_invoice_section_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_by_modern_invoice_section_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234:56789/invoiceSections/97531", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernInvoiceSectionId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py new file mode 100644 index 0000000000000..5f000f461b717 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_department_filter_by_start_end_date.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_for_department_filter_by_start_end_date.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234/departments/42425", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListForDepartmentFilterByStartEndDate.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py new file mode 100644 index 0000000000000..36be9fec79170 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/charges_list_for_enrollment_account_filter_by_start_end_date.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python charges_list_for_enrollment_account_filter_by_start_end_date.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.charges.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234/enrollmentAccounts/42425", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListForEnrollmentAccountFilterByStartEndDate.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py new file mode 100644 index 0000000000000..979f6ed0c2b4f --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/create_or_update_budget.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python create_or_update_budget.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.budgets.create_or_update( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + budget_name="TestBudget", + parameters={ + "eTag": '"1d34d016a593709"', + "properties": { + "amount": 100.65, + "category": "Cost", + "filter": { + "and": [ + { + "dimensions": { + "name": "ResourceId", + "operator": "In", + "values": [ + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Compute/virtualMachines/MSVM2", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Compute/virtualMachines/platformcloudplatformGeneric1", + ], + } + }, + {"tags": {"name": "category", "operator": "In", "values": ["Dev", "Prod"]}}, + {"tags": {"name": "department", "operator": "In", "values": ["engineering", "sales"]}}, + ] + }, + "notifications": { + "Actual_GreaterThan_80_Percent": { + "contactEmails": ["johndoe@contoso.com", "janesmith@contoso.com"], + "contactGroups": [ + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/microsoft.insights/actionGroups/SampleActionGroup" + ], + "contactRoles": ["Contributor", "Reader"], + "enabled": True, + "locale": "en-us", + "operator": "GreaterThan", + "threshold": 80, + "thresholdType": "Actual", + } + }, + "timeGrain": "Monthly", + "timePeriod": {"endDate": "2018-10-31T00:00:00Z", "startDate": "2017-10-01T00:00:00Z"}, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/CreateOrUpdateBudget.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py new file mode 100644 index 0000000000000..e28aa54c136ae --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/credit_summary_by_billing_profile.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python credit_summary_by_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.credits.get( + billing_account_id="1234:5678", + billing_profile_id="2468", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/CreditSummaryByBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py new file mode 100644 index 0000000000000..b8f8189f1e451 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python delete_budget.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.budgets.delete( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + budget_name="TestBudget", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/DeleteBudget.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py new file mode 100644 index 0000000000000..654c39418ad45 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python events_get_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.events.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsGetByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py new file mode 100644 index 0000000000000..727edac868589 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python events_get_by_billing_account_with_filters.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.events.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsGetByBillingAccountWithFilters.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py new file mode 100644 index 0000000000000..f84a0cec1ec36 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_list_by_billing_profile.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python events_list_by_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.events.list_by_billing_profile( + billing_account_id="1234:5678", + billing_profile_id="4268", + start_date="2019-09-01", + end_date="2019-10-31", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsListByBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py new file mode 100644 index 0000000000000..e63cf0b91405b --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py new file mode 100644 index 0000000000000..76381e1425e0a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_billing_account_with_filters.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_billing_account( + billing_account_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingAccountWithFilters.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py new file mode 100644 index 0000000000000..fe3344c1b346b --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_profile.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_billing_profile( + billing_account_id="1234:5678", + billing_profile_id="2468", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py new file mode 100644 index 0000000000000..f5bb3322ebe55 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_customer.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_customer( + billing_account_id="1234:5678", + customer_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByCustomer.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py new file mode 100644 index 0000000000000..74e95d98f92c7 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_customer_with_filters.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python lots_list_by_customer_with_filters.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.lots.list_by_customer( + billing_account_id="1234:5678", + customer_id="1234:5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByCustomerWithFilters.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py new file mode 100644 index 0000000000000..85fe45b1a08c6 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_billing_account_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByBillingAccountList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py new file mode 100644 index 0000000000000..ff44044a915ef --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_billing_account_list_for_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_billing_account_list_for_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByBillingAccountListForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py new file mode 100644 index 0000000000000..022527d5f93e4 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_department_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="providers/Microsoft.Billing/departments/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByDepartmentList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py new file mode 100644 index 0000000000000..21aacd1cec540 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_department_list_by_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_department_list_by_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="providers/Microsoft.Billing/departments/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByDepartment_ListByBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py new file mode 100644 index 0000000000000..6ca5344dc6990 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_account_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_enrollment_account_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="providers/Microsoft.Billing/enrollmentAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByEnrollmentAccountList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py new file mode 100644 index 0000000000000..a8db1c7722aba --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_enrollment_accounts_list_by_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_enrollment_accounts_list_by_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="providers/Microsoft.Billing/enrollmentAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByEnrollmentAccounts_ListByBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py new file mode 100644 index 0000000000000..4ee9b750a6046 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_management_group_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByManagementGroupList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py new file mode 100644 index 0000000000000..1418bb34ebde8 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_by_management_group_list_for_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_by_management_group_list_for_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.marketplaces.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByManagementGroup_ListForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py new file mode 100644 index 0000000000000..8db7d43c202b2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.marketplaces.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py new file mode 100644 index 0000000000000..cd0a50fb3de20 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list_for_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python marketplaces_list_for_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.marketplaces.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesListForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py new file mode 100644 index 0000000000000..0aa0424ba67f1 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python operation_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.operations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/OperationList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py new file mode 100644 index 0000000000000..50f503ce57fa8 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python price_sheet.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.price_sheet.get() + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheet.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py new file mode 100644 index 0000000000000..bb0b296619c5e --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python price_sheet_expand.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.price_sheet.get_by_billing_period( + billing_period_name="201801", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheetExpand.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py new file mode 100644 index 0000000000000..f0fc2a5d6a78d --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_for_billing_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python price_sheet_for_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="00000000-0000-0000-0000-000000000000", + ) + + response = client.price_sheet.get_by_billing_period( + billing_period_name="201801", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheetForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py new file mode 100644 index 0000000000000..305bb208f4f75 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_details.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_details.list_by_reservation_order( + reservation_order_id="00000000-0000-0000-0000-000000000000", + filter="properties/usageDate ge 2017-10-01 AND properties/usageDate le 2017-12-05", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetails.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py new file mode 100644 index 0000000000000..ad1a1e3d3a2e3 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_account_id.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_details_by_billing_account_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_details.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingAccountId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py new file mode 100644 index 0000000000000..868b9badee5aa --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_details_by_billing_profile_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_details.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345:2468/billingProfiles/13579", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingProfileId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py new file mode 100644 index 0000000000000..5e2576af19e9e --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_by_billing_profile_id_reservation_id.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_details_by_billing_profile_id_reservation_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_details.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345:2468/billingProfiles/13579", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingProfileIdReservationId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py new file mode 100644 index 0000000000000..648185c1e6d36 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details_with_reservation_id.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_details_with_reservation_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_details.list_by_reservation_order_and_reservation( + reservation_order_id="00000000-0000-0000-0000-000000000000", + reservation_id="00000000-0000-0000-0000-000000000000", + filter="properties/usageDate ge 2017-10-01 AND properties/usageDate le 2017-12-05", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsWithReservationId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py new file mode 100644 index 0000000000000..b568ac4ebc9ac --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_account.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendation_details_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendation_details.get( + resource_scope="providers/Microsoft.Billing/billingAccounts/000000", + scope="Shared", + region="eastus", + term="P1Y", + look_back_period="Last60Days", + product="Standard_DS14_v2", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py new file mode 100644 index 0000000000000..baadc975b9133 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_billing_profile.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendation_details_by_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendation_details.get( + resource_scope="providers/Microsoft.Billing/billingAccounts/00000000-0000-0000-0000-00000000:00000000-0000-0000-0000-00000000/billingProfiles/00000000-0000-0000-0000-00000000", + scope="Shared", + region="australiaeast", + term="P1Y", + look_back_period="Last7Days", + product="Standard_B2s", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py new file mode 100644 index 0000000000000..24db1707a9eb5 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_resource_group.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendation_details_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendation_details.get( + resource_scope="subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/testGroup", + scope="Single", + region="westus", + term="P3Y", + look_back_period="Last30Days", + product="Standard_DS13_v2", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py new file mode 100644 index 0000000000000..00fd41c3e879a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendation_details_by_subscription.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendation_details_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendation_details.get( + resource_scope="subscriptions/00000000-0000-0000-0000-00000000", + scope="Single", + region="westus", + term="P3Y", + look_back_period="Last30Days", + product="Standard_DS13_v2", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py new file mode 100644 index 0000000000000..b6e75bdc45ba4 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendations_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendations.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py new file mode 100644 index 0000000000000..34c18444bb674 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_profile.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendations_by_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendations.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/123456/billingProfiles/6420", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py new file mode 100644 index 0000000000000..38c93cb12b72a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_resource_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendations_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendations.list( + resource_scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testGroup", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py new file mode 100644 index 0000000000000..6f3953bfafe07 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_subscription.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendations_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendations.list( + resource_scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py new file mode 100644 index 0000000000000..b1eb8f1d440f0 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_recommendations_filter_by_subscription_for_scope_look_back_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_recommendations.list( + resource_scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsFilterBySubscriptionForScopeLookBackPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py new file mode 100644 index 0000000000000..483c4cc28fdca --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_daily.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list_by_reservation_order( + reservation_order_id="00000000-0000-0000-0000-000000000000", + grain="daily", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDaily.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py new file mode 100644 index 0000000000000..c8cb54c7f501f --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_account_id.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_daily_with_billing_account_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345", + grain="daily", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithBillingAccountId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py new file mode 100644 index 0000000000000..026c74b73209b --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_billing_profile_id.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_daily_with_billing_profile_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345:2468/billingProfiles/13579", + grain="daily", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithBillingProfileId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py new file mode 100644 index 0000000000000..fef5c801ffd34 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily_with_reservation_id.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_daily_with_reservation_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id="00000000-0000-0000-0000-000000000000", + reservation_id="00000000-0000-0000-0000-000000000000", + grain="daily", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithReservationId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py new file mode 100644 index 0000000000000..d422a0e925467 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_monthly.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list_by_reservation_order( + reservation_order_id="00000000-0000-0000-0000-000000000000", + grain="monthly", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthly.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py new file mode 100644 index 0000000000000..5364f59a6cdc0 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_account_id.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_monthly_with_billing_account_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345", + grain="monthly", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingAccountId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py new file mode 100644 index 0000000000000..26e7ace88c0ec --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_monthly_with_billing_profile_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345:2468/billingProfiles/13579", + grain="monthly", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingProfileId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py new file mode 100644 index 0000000000000..ecce4ed584218 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_billing_profile_id_reservation_id.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_monthly_with_billing_profile_id_reservation_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list( + resource_scope="providers/Microsoft.Billing/billingAccounts/12345:2468/billingProfiles/13579", + grain="monthly", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingProfileIdReservationId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py new file mode 100644 index 0000000000000..5d568bf216d25 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly_with_reservation_id.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_summaries_monthly_with_reservation_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id="00000000-0000-0000-0000-000000000000", + reservation_id="00000000-0000-0000-0000-000000000000", + grain="monthly", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithReservationId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py new file mode 100644 index 0000000000000..47ad9d5fefe6c --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_billing_profile_id.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_transactions_list_by_billing_profile_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_transactions.list_by_billing_profile( + billing_account_id="fcebaabc-fced-4284-a83d-79f83dee183c:45796ba8-988f-45ad-bea9-7b71fc6c7513_2018-09-30", + billing_profile_id="Z76D-SGAF-BG7-TGB", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationTransactionsListByBillingProfileId.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py new file mode 100644 index 0000000000000..e981da502b4c0 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_transactions_list_by_enrollment_number.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python reservation_transactions_list_by_enrollment_number.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.reservation_transactions.list( + billing_account_id="123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationTransactionsListByEnrollmentNumber.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py new file mode 100644 index 0000000000000..d1687eeaea609 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python tags.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.tags.get( + scope="providers/Microsoft.CostManagement/billingAccounts/1234", + ) + print(response) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/Tags.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py new file mode 100644 index 0000000000000..1bd9e81a704a9 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_expand.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsExpand.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py new file mode 100644 index 0000000000000..629b97dd45a8e --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsList.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py new file mode 100644 index 0000000000000..b7670a59ed049 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_billing_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py new file mode 100644 index 0000000000000..1ae750575929c --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_department.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/Departments/1234", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py new file mode 100644 index 0000000000000..b30348d977605 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_enrollment_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/EnrollmentAccounts/1234", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py new file mode 100644 index 0000000000000..bea5ad73b4128 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_management_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py new file mode 100644 index 0000000000000..fa5ce256e80a2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_mca_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234:56789", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCABillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py new file mode 100644 index 0000000000000..26898092a093a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_billing_profile.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_mca_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234:56789/billingProfiles/2468", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCABillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py new file mode 100644 index 0000000000000..9dc99a6b98a58 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_customer.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_mca_customer.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234:56789/customers/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCACustomer.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py new file mode 100644 index 0000000000000..31956a23ef8d6 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_mca_invoice_section.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_mca_invoice_section.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234:56789/invoiceSections/98765", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCAInvoiceSection.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py new file mode 100644 index 0000000000000..74a175954cb5c --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_actual_cost.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_metric_actual_cost.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricActualCost.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py new file mode 100644 index 0000000000000..8f8e9287f20eb --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_amortized_cost.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_metric_amortized_cost.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricAmortizedCost.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py new file mode 100644 index 0000000000000..5fd433c0db0e9 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_by_metric_usage.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_by_metric_usage.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricUsage.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py new file mode 100644 index 0000000000000..0f46035be3694 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_filter_by_tag.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_filter_by_tag.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListFilterByTag.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py new file mode 100644 index 0000000000000..2bc29d1596302 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_for_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py new file mode 100644 index 0000000000000..2f72f2a0cfb06 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_billing_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_for_billing_period_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/BillingAccounts/1234", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py new file mode 100644 index 0000000000000..462999a9dc8ac --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_department.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_for_billing_period_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/Departments/1234", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py new file mode 100644 index 0000000000000..ffec807c47c57 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_enrollment_account.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_for_billing_period_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="providers/Microsoft.Billing/EnrollmentAccounts/1234", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py new file mode 100644 index 0000000000000..dce956c8dbd4a --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list_for_billing_period_by_management_group.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-consumption +# USAGE + python usage_details_list_for_billing_period_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = ConsumptionManagementClient( + credential=DefaultAzureCredential(), + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.usage_details.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByManagementGroup.json +if __name__ == "__main__": + main()