diff --git a/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md b/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md index 728ecaec94e3..ee0354e5dace 100644 --- a/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md +++ b/sdk/consumption/azure-mgmt-consumption/CHANGELOG.md @@ -1,5 +1,114 @@ # Release History +## 11.0.0b2 (2026-05-22) + +### Features Added + + - Client `ConsumptionManagementClient` added parameter `cloud_setting` in method `__init__` + - Client `ConsumptionManagementClient` added method `send_request` + - Model `Balance` added property `system_data` + - Model `Budget` added property `system_data` + - Model `ChargeSummary` added property `e_tag` + - Model `ChargeSummary` added property `system_data` + - Model `CreditSummary` added property `tags` + - Model `CreditSummary` added property `system_data` + - Model `EventSummary` added property `properties` + - Model `EventSummary` added property `system_data` + - Model `LegacyChargeSummary` added property `e_tag` + - Model `LegacyChargeSummary` added property `system_data` + - Model `LegacyReservationRecommendation` added property `properties` + - Model `LegacyReservationRecommendation` added property `system_data` + - Model `LegacyReservationRecommendationProperties` added property `last_usage_date` + - Model `LegacyReservationRecommendationProperties` added property `total_hours` + - Model `LegacySharedScopeReservationRecommendationProperties` added property `last_usage_date` + - Model `LegacySharedScopeReservationRecommendationProperties` added property `total_hours` + - Model `LegacySingleScopeReservationRecommendationProperties` added property `last_usage_date` + - Model `LegacySingleScopeReservationRecommendationProperties` added property `total_hours` + - Model `LegacyUsageDetail` added property `system_data` + - Model `LotSummary` added property `properties` + - Model `LotSummary` added property `system_data` + - Model `ManagementGroupAggregatedCostResult` added property `properties` + - Model `ManagementGroupAggregatedCostResult` added property `system_data` + - Model `Marketplace` added property `system_data` + - Model `ModernChargeSummary` added property `e_tag` + - Model `ModernChargeSummary` added property `system_data` + - Model `ModernReservationRecommendation` added property `properties` + - Model `ModernReservationRecommendation` added property `system_data` + - Model `ModernReservationRecommendationProperties` added property `last_usage_date` + - Model `ModernReservationRecommendationProperties` added property `total_hours` + - Model `ModernReservationTransaction` added property `system_data` + - Model `ModernSharedScopeReservationRecommendationProperties` added property `last_usage_date` + - Model `ModernSharedScopeReservationRecommendationProperties` added property `total_hours` + - Model `ModernSingleScopeReservationRecommendationProperties` added property `last_usage_date` + - Model `ModernSingleScopeReservationRecommendationProperties` added property `total_hours` + - Model `ModernUsageDetail` added property `system_data` + - Model `PriceSheetProperties` added property `savings_plan` + - Model `PriceSheetResult` added property `properties` + - Model `PriceSheetResult` added property `system_data` + - Model `ProxyResource` added property `system_data` + - Model `ReservationDetail` added property `system_data` + - Model `ReservationRecommendation` added property `system_data` + - Model `ReservationRecommendationDetailsModel` added property `properties` + - Model `ReservationRecommendationDetailsModel` added property `system_data` + - Model `ReservationSummary` added property `system_data` + - Model `ReservationTransaction` added property `properties` + - Model `ReservationTransaction` added property `system_data` + - Model `Resource` added property `system_data` + - Model `TagsResult` added property `properties` + - Model `TagsResult` added property `system_data` + - Enum `Term` added member `P1_M` + - Model `UsageDetail` added property `system_data` + - Added enum `CreatedByType` + - Added model `ErrorAdditionalInfo` + - Added model `ExtensionResource` + - Added model `OperationStatus` + - Added enum `OperationStatusType` + - Added enum `OrganizationType` + - Added model `PricesheetDownloadProperties` + - Added model `SavingsPlan` + - Added model `SystemData` + - Operation group `PriceSheetOperations` added method `begin_download_by_billing_account_period` + - Operation group `ReservationRecommendationDetailsOperations` added parameter `filter` in method `get` + - Operation group `ReservationTransactionsOperations` added parameter `use_markup_if_partner` in method `list` + - Operation group `ReservationTransactionsOperations` added parameter `preview_markup_percentage` in method `list` + +### Breaking Changes + + - This version introduces new hybrid models which have dual dictionary and model nature. Please follow https://aka.ms/azsdk/python/migrate/hybrid-models for migration. + - For the method breakings, please refer to https://aka.ms/azsdk/python/migrate/operations for migration. + - Model `BudgetComparisonExpression` renamed its instance variable `values` to `values_property` + - Model `ChargeSummary` deleted or renamed its instance variable `etag` + - Model `ChargeSummary` deleted or renamed its instance variable `tags` + - Model `EventSummary` moved instance variable `transaction_date`, `description`, `new_credit`, `adjustments`, `credit_expired`, `charges`, `closed_balance`, `event_type`, `invoice_number`, `billing_profile_id`, `billing_profile_display_name`, `lot_id`, `lot_source`, `canceled_credit`, `credit_currency`, `billing_currency`, `reseller`, `credit_expired_in_billing_currency`, `new_credit_in_billing_currency`, `adjustments_in_billing_currency`, `charges_in_billing_currency`, `closed_balance_in_billing_currency` and `e_tag_properties_e_tag` under property `properties` whose type is `EventProperties` + - Model `LegacyReservationRecommendation` moved instance variable `look_back_period`, `instance_flexibility_ratio`, `instance_flexibility_group`, `normalized_size`, `recommended_quantity_normalized`, `meter_id`, `resource_type`, `term`, `cost_with_no_reserved_instances`, `recommended_quantity`, `total_cost_with_reserved_instances`, `net_savings`, `first_usage_date`, `scope` and `sku_properties` under property `properties` whose type is `LegacyReservationRecommendationProperties` + - Model `LotSummary` moved instance variable `original_amount`, `closed_balance`, `source`, `start_date`, `expiration_date`, `po_number`, `purchased_date`, `status`, `credit_currency`, `billing_currency`, `original_amount_in_billing_currency`, `closed_balance_in_billing_currency`, `reseller` and `e_tag_properties_e_tag` under property `properties` whose type is `LotProperties` + - Model `ManagementGroupAggregatedCostResult` moved instance variable `billing_period_id`, `usage_start`, `usage_end`, `azure_charges`, `marketplace_charges`, `charges_billed_separately`, `currency`, `children`, `included_subscriptions` and `excluded_subscriptions` under property `properties` whose type is `ManagementGroupAggregatedCostProperties` + - Model `ModernReservationRecommendation` moved instance variable `location_properties_location`, `look_back_period`, `instance_flexibility_ratio`, `instance_flexibility_group`, `normalized_size`, `recommended_quantity_normalized`, `meter_id`, `term`, `cost_with_no_reserved_instances`, `recommended_quantity`, `resource_type`, `total_cost_with_reserved_instances`, `net_savings`, `first_usage_date`, `scope`, `sku_properties` and `sku_name` under property `properties` whose type is `ModernReservationRecommendationProperties` + - Model `PriceSheetResult` moved instance variable `pricesheets`, `next_link` and `download` under property `properties` whose type is `PriceSheetModel` + - Model `ProxyResource` deleted or renamed its instance variable `e_tag` + - Model `ReservationRecommendationDetailsModel` moved instance variable `currency`, `resource`, `resource_group`, `savings`, `scope` and `usage` under property `properties` whose type is `ReservationRecommendationDetailsProperties` + - Model `ReservationTransaction` moved instance variable `event_date`, `reservation_order_id`, `description`, `event_type`, `quantity`, `amount`, `currency`, `reservation_order_name`, `purchasing_enrollment`, `purchasing_subscription_guid`, `purchasing_subscription_name`, `arm_sku_name`, `term`, `region`, `account_name`, `account_owner_email`, `department_name`, `cost_center`, `current_enrollment`, `billing_frequency`, `billing_month`, `monetary_commitment` and `overage` under property `properties` whose type is `LegacyReservationTransactionProperties` + - Model `Resource` deleted or renamed its instance variable `etag` + - Model `Resource` deleted or renamed its instance variable `tags` + - Model `TagsResult` moved instance variable `tags`, `next_link` and `previous_link` under property `properties` whose type is `TagProperties` + - Renamed model `ErrorDetails` to `ErrorDetail` + - Method `ChargesOperations.list` changed its parameter `start_date`/`end_date`/`apply` from `positional_or_keyword` to `keyword_only` + - Method `EventsOperations.list_by_billing_profile` changed its parameter `start_date`/`end_date` from `positional_or_keyword` to `keyword_only` + - Method `MarketplacesOperations.list` changed its parameter `skiptoken` from `positional_or_keyword` to `keyword_only` + - Method `PriceSheetOperations.get` changed its parameter `expand`/`skiptoken` from `positional_or_keyword` to `keyword_only` + - Method `PriceSheetOperations.get_by_billing_period` changed its parameter `expand`/`skiptoken` from `positional_or_keyword` to `keyword_only` + - Method `ReservationRecommendationDetailsOperations.get` changed its parameter `scope`/`region`/`term`/`look_back_period`/`product` from `positional_or_keyword` to `keyword_only` + - Method `ReservationsDetailsOperations.list` changed its parameter `start_date`/`end_date`/`reservation_id`/`reservation_order_id` from `positional_or_keyword` to `keyword_only` + - Method `ReservationsSummariesOperations.list` changed its parameter `grain`/`start_date`/`end_date`/`reservation_id`/`reservation_order_id` from `positional_or_keyword` to `keyword_only` + - Method `ReservationsSummariesOperations.list_by_reservation_order` changed its parameter `grain` from `positional_or_keyword` to `keyword_only` + - Method `ReservationsSummariesOperations.list_by_reservation_order_and_reservation` changed its parameter `grain` from `positional_or_keyword` to `keyword_only` + - Method `UsageDetailsOperations.list` changed its parameter `expand`/`skiptoken`/`metric` from `positional_or_keyword` to `keyword_only` + +### Other Changes + + - Deleted model `Events`/`Lots` which actually were not used by SDK users + - Deleted model `DownloadProperties`/`LegacyReservationTransaction`/`ReservationTransactionResource`/`ResourceAttributes` which actually were not used by SDK users + ## 11.0.0b1 (2022-12-07) ### Features Added diff --git a/sdk/consumption/azure-mgmt-consumption/MANIFEST.in b/sdk/consumption/azure-mgmt-consumption/MANIFEST.in index 11654dcdbe1b..7aea2c664694 100644 --- a/sdk/consumption/azure-mgmt-consumption/MANIFEST.in +++ b/sdk/consumption/azure-mgmt-consumption/MANIFEST.in @@ -1,8 +1,7 @@ -include _meta.json -recursive-include tests *.py *.json -recursive-include samples *.py *.md include *.md -include azure/__init__.py -include azure/mgmt/__init__.py include LICENSE include azure/mgmt/consumption/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py diff --git a/sdk/consumption/azure-mgmt-consumption/README.md b/sdk/consumption/azure-mgmt-consumption/README.md index d18e0a3b34fa..8fef28a1712c 100644 --- a/sdk/consumption/azure-mgmt-consumption/README.md +++ b/sdk/consumption/azure-mgmt-consumption/README.md @@ -1,28 +1,61 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Consumption Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.10+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ -# Usage +## Getting started +### Prerequisites -To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt) - -For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/consumption) -Code samples for this package can be found at [Consumption](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com. -Additional code samples for different Azure services are available at [Samples Repo](https://github.com/Azure-Samples/azure-samples-python-management/tree/main/samples/consumption) +- Python 3.10+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) +### Install the package -# Provide Feedback +```bash +pip install azure-mgmt-consumption +pip install azure-identity +``` -If you encounter any bugs or have suggestions, please file an issue in the -[Issues](https://github.com/Azure/azure-sdk-for-python/issues) -section of the project. +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.consumption import ConsumptionManagementClient +import os +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = ConsumptionManagementClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` +## Examples +Code samples for this package can be found at: +- [Search Consumption](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/consumption/azure-mgmt-consumption/_meta.json b/sdk/consumption/azure-mgmt-consumption/_meta.json deleted file mode 100644 index 2bff1506a305..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "1be09531e4c6edeafde41d6562371566d39669e8", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", - "use": [ - "@autorest/python@6.2.7", - "@autorest/modelerfour@4.24.3" - ], - "autorest_command": "autorest specification/consumption/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/home/vsts/work/1/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/_metadata.json b/sdk/consumption/azure-mgmt-consumption/_metadata.json new file mode 100644 index 000000000000..70874fdaf286 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/_metadata.json @@ -0,0 +1,10 @@ +{ + "apiVersion": "2024-08-01", + "apiVersions": { + "Microsoft.Consumption": "2024-08-01" + }, + "commit": "aa9df243e9a6ecf6110383e079d622a87bd405d3", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/consumption/resource-manager/Microsoft.Consumption/Consumption", + "emitterVersion": "0.62.1" +} \ No newline at end of file diff --git a/sdk/consumption/azure-mgmt-consumption/apiview-properties.json b/sdk/consumption/azure-mgmt-consumption/apiview-properties.json new file mode 100644 index 000000000000..7e2fee7867b7 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/apiview-properties.json @@ -0,0 +1,176 @@ +{ + "CrossLanguagePackageId": "Microsoft.Consumption", + "CrossLanguageDefinitionId": { + "azure.mgmt.consumption.models.Amount": "Microsoft.Consumption.Amount", + "azure.mgmt.consumption.models.AmountWithExchangeRate": "Microsoft.Consumption.AmountWithExchangeRate", + "azure.mgmt.consumption.models.Resource": "Azure.ResourceManager.CommonTypes.Resource", + "azure.mgmt.consumption.models.Balance": "Microsoft.Consumption.Balance", + "azure.mgmt.consumption.models.BalanceProperties": "Microsoft.Consumption.BalanceProperties", + "azure.mgmt.consumption.models.BalancePropertiesAdjustmentDetailsItem": "Microsoft.Consumption.BalancePropertiesAdjustmentDetailsItem", + "azure.mgmt.consumption.models.BalancePropertiesNewPurchasesDetailsItem": "Microsoft.Consumption.BalancePropertiesNewPurchasesDetailsItem", + "azure.mgmt.consumption.models.ExtensionResource": "Azure.ResourceManager.CommonTypes.ExtensionResource", + "azure.mgmt.consumption.models.Budget": "Microsoft.Consumption.Budget", + "azure.mgmt.consumption.models.BudgetComparisonExpression": "Microsoft.Consumption.BudgetComparisonExpression", + "azure.mgmt.consumption.models.BudgetFilter": "Microsoft.Consumption.BudgetFilter", + "azure.mgmt.consumption.models.BudgetFilterProperties": "Microsoft.Consumption.BudgetFilterProperties", + "azure.mgmt.consumption.models.BudgetProperties": "Microsoft.Consumption.BudgetProperties", + "azure.mgmt.consumption.models.BudgetTimePeriod": "Microsoft.Consumption.BudgetTimePeriod", + "azure.mgmt.consumption.models.ChargesListResult": "Microsoft.Consumption.ChargesListResult", + "azure.mgmt.consumption.models.ProxyResource": "Azure.ResourceManager.CommonTypes.ProxyResource", + "azure.mgmt.consumption.models.ChargeSummary": "Microsoft.Consumption.ChargeSummary", + "azure.mgmt.consumption.models.CreditBalanceSummary": "Microsoft.Consumption.CreditBalanceSummary", + "azure.mgmt.consumption.models.CreditSummary": "Microsoft.Consumption.CreditSummary", + "azure.mgmt.consumption.models.CreditSummaryProperties": "Microsoft.Consumption.CreditSummaryProperties", + "azure.mgmt.consumption.models.CurrentSpend": "Microsoft.Consumption.CurrentSpend", + "azure.mgmt.consumption.models.ErrorAdditionalInfo": "Azure.ResourceManager.CommonTypes.ErrorAdditionalInfo", + "azure.mgmt.consumption.models.ErrorDetail": "Azure.ResourceManager.CommonTypes.ErrorDetail", + "azure.mgmt.consumption.models.ErrorResponse": "Azure.ResourceManager.CommonTypes.ErrorResponse", + "azure.mgmt.consumption.models.EventProperties": "Microsoft.Consumption.EventProperties", + "azure.mgmt.consumption.models.EventSummary": "Microsoft.Consumption.EventSummary", + "azure.mgmt.consumption.models.ForecastSpend": "Microsoft.Consumption.ForecastSpend", + "azure.mgmt.consumption.models.HighCasedErrorDetails": "Microsoft.Consumption.HighCasedErrorDetails", + "azure.mgmt.consumption.models.HighCasedErrorResponse": "Microsoft.Consumption.HighCasedErrorResponse", + "azure.mgmt.consumption.models.LegacyChargeSummary": "Microsoft.Consumption.LegacyChargeSummary", + "azure.mgmt.consumption.models.LegacyChargeSummaryProperties": "Microsoft.Consumption.LegacyChargeSummaryProperties", + "azure.mgmt.consumption.models.ReservationRecommendation": "Microsoft.Consumption.ReservationRecommendation", + "azure.mgmt.consumption.models.LegacyReservationRecommendation": "Microsoft.Consumption.LegacyReservationRecommendation", + "azure.mgmt.consumption.models.LegacyReservationRecommendationProperties": "Microsoft.Consumption.LegacyReservationRecommendationProperties", + "azure.mgmt.consumption.models.LegacyReservationTransactionProperties": "Microsoft.Consumption.LegacyReservationTransactionProperties", + "azure.mgmt.consumption.models.LegacySharedScopeReservationRecommendationProperties": "Microsoft.Consumption.LegacySharedScopeReservationRecommendationProperties", + "azure.mgmt.consumption.models.LegacySingleScopeReservationRecommendationProperties": "Microsoft.Consumption.LegacySingleScopeReservationRecommendationProperties", + "azure.mgmt.consumption.models.UsageDetail": "Microsoft.Consumption.UsageDetail", + "azure.mgmt.consumption.models.LegacyUsageDetail": "Microsoft.Consumption.LegacyUsageDetail", + "azure.mgmt.consumption.models.LegacyUsageDetailProperties": "Microsoft.Consumption.LegacyUsageDetailProperties", + "azure.mgmt.consumption.models.LotProperties": "Microsoft.Consumption.LotProperties", + "azure.mgmt.consumption.models.LotSummary": "Microsoft.Consumption.LotSummary", + "azure.mgmt.consumption.models.ManagementGroupAggregatedCostProperties": "Microsoft.Consumption.ManagementGroupAggregatedCostProperties", + "azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult": "Microsoft.Consumption.ManagementGroupAggregatedCostResult", + "azure.mgmt.consumption.models.Marketplace": "Microsoft.Consumption.Marketplace", + "azure.mgmt.consumption.models.MarketplaceProperties": "Microsoft.Consumption.MarketplaceProperties", + "azure.mgmt.consumption.models.MeterDetails": "Microsoft.Consumption.MeterDetails", + "azure.mgmt.consumption.models.MeterDetailsResponse": "Microsoft.Consumption.MeterDetailsResponse", + "azure.mgmt.consumption.models.ModernChargeSummary": "Microsoft.Consumption.ModernChargeSummary", + "azure.mgmt.consumption.models.ModernChargeSummaryProperties": "Microsoft.Consumption.ModernChargeSummaryProperties", + "azure.mgmt.consumption.models.ModernReservationRecommendation": "Microsoft.Consumption.ModernReservationRecommendation", + "azure.mgmt.consumption.models.ModernReservationRecommendationProperties": "Microsoft.Consumption.ModernReservationRecommendationProperties", + "azure.mgmt.consumption.models.ModernReservationTransaction": "Microsoft.Consumption.ModernReservationTransaction", + "azure.mgmt.consumption.models.ModernReservationTransactionProperties": "Microsoft.Consumption.ModernReservationTransactionProperties", + "azure.mgmt.consumption.models.ModernSharedScopeReservationRecommendationProperties": "Microsoft.Consumption.ModernSharedScopeReservationRecommendationProperties", + "azure.mgmt.consumption.models.ModernSingleScopeReservationRecommendationProperties": "Microsoft.Consumption.ModernSingleScopeReservationRecommendationProperties", + "azure.mgmt.consumption.models.ModernUsageDetail": "Microsoft.Consumption.ModernUsageDetail", + "azure.mgmt.consumption.models.ModernUsageDetailProperties": "Microsoft.Consumption.ModernUsageDetailProperties", + "azure.mgmt.consumption.models.Notification": "Microsoft.Consumption.Notification", + "azure.mgmt.consumption.models.Operation": "Microsoft.Consumption.Operation", + "azure.mgmt.consumption.models.OperationDisplay": "Microsoft.Consumption.OperationDisplay", + "azure.mgmt.consumption.models.OperationStatus": "Microsoft.Consumption.OperationStatus", + "azure.mgmt.consumption.models.PricesheetDownloadProperties": "Microsoft.Consumption.PricesheetDownloadProperties", + "azure.mgmt.consumption.models.PriceSheetModel": "Microsoft.Consumption.PriceSheetModel", + "azure.mgmt.consumption.models.PriceSheetProperties": "Microsoft.Consumption.PriceSheetProperties", + "azure.mgmt.consumption.models.PriceSheetResult": "Microsoft.Consumption.PriceSheetResult", + "azure.mgmt.consumption.models.Reseller": "Microsoft.Consumption.Reseller", + "azure.mgmt.consumption.models.ReservationDetail": "Microsoft.Consumption.ReservationDetail", + "azure.mgmt.consumption.models.ReservationDetailProperties": "Microsoft.Consumption.ReservationDetailProperties", + "azure.mgmt.consumption.models.ReservationRecommendationDetailsCalculatedSavingsProperties": "Microsoft.Consumption.ReservationRecommendationDetailsCalculatedSavingsProperties", + "azure.mgmt.consumption.models.ReservationRecommendationDetailsModel": "Microsoft.Consumption.ReservationRecommendationDetailsModel", + "azure.mgmt.consumption.models.ReservationRecommendationDetailsProperties": "Microsoft.Consumption.ReservationRecommendationDetailsProperties", + "azure.mgmt.consumption.models.ReservationRecommendationDetailsResourceProperties": "Microsoft.Consumption.ReservationRecommendationDetailsResourceProperties", + "azure.mgmt.consumption.models.ReservationRecommendationDetailsSavingsProperties": "Microsoft.Consumption.ReservationRecommendationDetailsSavingsProperties", + "azure.mgmt.consumption.models.ReservationRecommendationDetailsUsageProperties": "Microsoft.Consumption.ReservationRecommendationDetailsUsageProperties", + "azure.mgmt.consumption.models.ReservationSummary": "Microsoft.Consumption.ReservationSummary", + "azure.mgmt.consumption.models.ReservationSummaryProperties": "Microsoft.Consumption.ReservationSummaryProperties", + "azure.mgmt.consumption.models.ReservationTransaction": "Microsoft.Consumption.ReservationTransaction", + "azure.mgmt.consumption.models.SavingsPlan": "Microsoft.Consumption.SavingsPlan", + "azure.mgmt.consumption.models.SkuProperty": "Microsoft.Consumption.SkuProperty", + "azure.mgmt.consumption.models.SystemData": "Azure.ResourceManager.CommonTypes.SystemData", + "azure.mgmt.consumption.models.Tag": "Microsoft.Consumption.Tag", + "azure.mgmt.consumption.models.TagProperties": "Microsoft.Consumption.TagProperties", + "azure.mgmt.consumption.models.TagsResult": "Microsoft.Consumption.TagsResult", + "azure.mgmt.consumption.models.CreatedByType": "Azure.ResourceManager.CommonTypes.createdByType", + "azure.mgmt.consumption.models.OperationStatusType": "Microsoft.Consumption.OperationStatusType", + "azure.mgmt.consumption.models.CategoryType": "Microsoft.Consumption.CategoryType", + "azure.mgmt.consumption.models.TimeGrainType": "Microsoft.Consumption.TimeGrainType", + "azure.mgmt.consumption.models.BudgetOperatorType": "Microsoft.Consumption.BudgetOperatorType", + "azure.mgmt.consumption.models.OperatorType": "Microsoft.Consumption.OperatorType", + "azure.mgmt.consumption.models.ThresholdType": "Microsoft.Consumption.ThresholdType", + "azure.mgmt.consumption.models.CultureCode": "Microsoft.Consumption.CultureCode", + "azure.mgmt.consumption.models.UsageDetailsKind": "Microsoft.Consumption.UsageDetailsKind", + "azure.mgmt.consumption.models.PricingModelType": "Microsoft.Consumption.PricingModelType", + "azure.mgmt.consumption.models.Metrictype": "Microsoft.Consumption.Metrictype", + "azure.mgmt.consumption.models.ChargeSummaryKind": "Microsoft.Consumption.ChargeSummaryKind", + "azure.mgmt.consumption.models.BillingFrequency": "Microsoft.Consumption.BillingFrequency", + "azure.mgmt.consumption.models.Datagrain": "Microsoft.Consumption.Datagrain", + "azure.mgmt.consumption.models.ReservationRecommendationKind": "Microsoft.Consumption.ReservationRecommendationKind", + "azure.mgmt.consumption.models.Scope": "Microsoft.Consumption.Scope", + "azure.mgmt.consumption.models.Term": "Microsoft.Consumption.Term", + "azure.mgmt.consumption.models.LookBackPeriod": "Microsoft.Consumption.LookBackPeriod", + "azure.mgmt.consumption.models.EventType": "Microsoft.Consumption.EventType", + "azure.mgmt.consumption.models.LotSource": "Microsoft.Consumption.LotSource", + "azure.mgmt.consumption.models.Status": "Microsoft.Consumption.Status", + "azure.mgmt.consumption.models.OrganizationType": "Microsoft.Consumption.OrganizationType", + "azure.mgmt.consumption.operations.Operations.list": "Azure.ResourceManager.Legacy.Operations.list", + "azure.mgmt.consumption.aio.operations.Operations.list": "Azure.ResourceManager.Legacy.Operations.list", + "azure.mgmt.consumption.operations.PriceSheetOperations.get_by_billing_period": "Microsoft.Consumption.PriceSheet.getByBillingPeriod", + "azure.mgmt.consumption.aio.operations.PriceSheetOperations.get_by_billing_period": "Microsoft.Consumption.PriceSheet.getByBillingPeriod", + "azure.mgmt.consumption.operations.PriceSheetOperations.get": "Microsoft.Consumption.PriceSheetResults.get", + "azure.mgmt.consumption.aio.operations.PriceSheetOperations.get": "Microsoft.Consumption.PriceSheetResults.get", + "azure.mgmt.consumption.operations.PriceSheetOperations.begin_download_by_billing_account_period": "Microsoft.Consumption.PriceSheetOperationGroup.downloadByBillingAccountPeriod", + "azure.mgmt.consumption.aio.operations.PriceSheetOperations.begin_download_by_billing_account_period": "Microsoft.Consumption.PriceSheetOperationGroup.downloadByBillingAccountPeriod", + "azure.mgmt.consumption.operations.BudgetsOperations.get": "Microsoft.Consumption.Budgets.get", + "azure.mgmt.consumption.aio.operations.BudgetsOperations.get": "Microsoft.Consumption.Budgets.get", + "azure.mgmt.consumption.operations.BudgetsOperations.create_or_update": "Microsoft.Consumption.Budgets.createOrUpdate", + "azure.mgmt.consumption.aio.operations.BudgetsOperations.create_or_update": "Microsoft.Consumption.Budgets.createOrUpdate", + "azure.mgmt.consumption.operations.BudgetsOperations.delete": "Microsoft.Consumption.Budgets.delete", + "azure.mgmt.consumption.aio.operations.BudgetsOperations.delete": "Microsoft.Consumption.Budgets.delete", + "azure.mgmt.consumption.operations.BudgetsOperations.list": "Microsoft.Consumption.Budgets.list", + "azure.mgmt.consumption.aio.operations.BudgetsOperations.list": "Microsoft.Consumption.Budgets.list", + "azure.mgmt.consumption.operations.CreditsOperations.get": "Microsoft.Consumption.CreditSummaries.get", + "azure.mgmt.consumption.aio.operations.CreditsOperations.get": "Microsoft.Consumption.CreditSummaries.get", + "azure.mgmt.consumption.operations.UsageDetailsOperations.list": "Microsoft.Consumption.UsageDetailsOperationGroup.list", + "azure.mgmt.consumption.aio.operations.UsageDetailsOperations.list": "Microsoft.Consumption.UsageDetailsOperationGroup.list", + "azure.mgmt.consumption.operations.MarketplacesOperations.list": "Microsoft.Consumption.MarketplacesOperationGroup.list", + "azure.mgmt.consumption.aio.operations.MarketplacesOperations.list": "Microsoft.Consumption.MarketplacesOperationGroup.list", + "azure.mgmt.consumption.operations.TagsOperations.get": "Microsoft.Consumption.TagsOperationGroup.get", + "azure.mgmt.consumption.aio.operations.TagsOperations.get": "Microsoft.Consumption.TagsOperationGroup.get", + "azure.mgmt.consumption.operations.ChargesOperations.list": "Microsoft.Consumption.ChargesOperationGroup.list", + "azure.mgmt.consumption.aio.operations.ChargesOperations.list": "Microsoft.Consumption.ChargesOperationGroup.list", + "azure.mgmt.consumption.operations.BalancesOperations.get_by_billing_account": "Microsoft.Consumption.BalancesOperationGroup.getByBillingAccount", + "azure.mgmt.consumption.aio.operations.BalancesOperations.get_by_billing_account": "Microsoft.Consumption.BalancesOperationGroup.getByBillingAccount", + "azure.mgmt.consumption.operations.BalancesOperations.get_for_billing_period_by_billing_account": "Microsoft.Consumption.BalancesOperationGroup.getForBillingPeriodByBillingAccount", + "azure.mgmt.consumption.aio.operations.BalancesOperations.get_for_billing_period_by_billing_account": "Microsoft.Consumption.BalancesOperationGroup.getForBillingPeriodByBillingAccount", + "azure.mgmt.consumption.operations.ReservationsSummariesOperations.list_by_reservation_order": "Microsoft.Consumption.ReservationsSummariesOperationGroup.listByReservationOrder", + "azure.mgmt.consumption.aio.operations.ReservationsSummariesOperations.list_by_reservation_order": "Microsoft.Consumption.ReservationsSummariesOperationGroup.listByReservationOrder", + "azure.mgmt.consumption.operations.ReservationsSummariesOperations.list_by_reservation_order_and_reservation": "Microsoft.Consumption.ReservationsSummariesOperationGroup.listByReservationOrderAndReservation", + "azure.mgmt.consumption.aio.operations.ReservationsSummariesOperations.list_by_reservation_order_and_reservation": "Microsoft.Consumption.ReservationsSummariesOperationGroup.listByReservationOrderAndReservation", + "azure.mgmt.consumption.operations.ReservationsSummariesOperations.list": "Microsoft.Consumption.ReservationsSummariesOperationGroup.list", + "azure.mgmt.consumption.aio.operations.ReservationsSummariesOperations.list": "Microsoft.Consumption.ReservationsSummariesOperationGroup.list", + "azure.mgmt.consumption.operations.ReservationsDetailsOperations.list_by_reservation_order": "Microsoft.Consumption.ReservationsDetailsOperationGroup.listByReservationOrder", + "azure.mgmt.consumption.aio.operations.ReservationsDetailsOperations.list_by_reservation_order": "Microsoft.Consumption.ReservationsDetailsOperationGroup.listByReservationOrder", + "azure.mgmt.consumption.operations.ReservationsDetailsOperations.list_by_reservation_order_and_reservation": "Microsoft.Consumption.ReservationsDetailsOperationGroup.listByReservationOrderAndReservation", + "azure.mgmt.consumption.aio.operations.ReservationsDetailsOperations.list_by_reservation_order_and_reservation": "Microsoft.Consumption.ReservationsDetailsOperationGroup.listByReservationOrderAndReservation", + "azure.mgmt.consumption.operations.ReservationsDetailsOperations.list": "Microsoft.Consumption.ReservationsDetailsOperationGroup.list", + "azure.mgmt.consumption.aio.operations.ReservationsDetailsOperations.list": "Microsoft.Consumption.ReservationsDetailsOperationGroup.list", + "azure.mgmt.consumption.operations.ReservationRecommendationsOperations.list": "Microsoft.Consumption.ReservationRecommendationsOperationGroup.list", + "azure.mgmt.consumption.aio.operations.ReservationRecommendationsOperations.list": "Microsoft.Consumption.ReservationRecommendationsOperationGroup.list", + "azure.mgmt.consumption.operations.ReservationRecommendationDetailsOperations.get": "Microsoft.Consumption.ReservationRecommendationDetailsOperationGroup.get", + "azure.mgmt.consumption.aio.operations.ReservationRecommendationDetailsOperations.get": "Microsoft.Consumption.ReservationRecommendationDetailsOperationGroup.get", + "azure.mgmt.consumption.operations.ReservationTransactionsOperations.list": "Microsoft.Consumption.ReservationTransactionsOperationGroup.list", + "azure.mgmt.consumption.aio.operations.ReservationTransactionsOperations.list": "Microsoft.Consumption.ReservationTransactionsOperationGroup.list", + "azure.mgmt.consumption.operations.ReservationTransactionsOperations.list_by_billing_profile": "Microsoft.Consumption.ReservationTransactionsOperationGroup.listByBillingProfile", + "azure.mgmt.consumption.aio.operations.ReservationTransactionsOperations.list_by_billing_profile": "Microsoft.Consumption.ReservationTransactionsOperationGroup.listByBillingProfile", + "azure.mgmt.consumption.operations.AggregatedCostOperations.get_by_management_group": "Microsoft.Consumption.AggregatedCostOperationGroup.getByManagementGroup", + "azure.mgmt.consumption.aio.operations.AggregatedCostOperations.get_by_management_group": "Microsoft.Consumption.AggregatedCostOperationGroup.getByManagementGroup", + "azure.mgmt.consumption.operations.AggregatedCostOperations.get_for_billing_period_by_management_group": "Microsoft.Consumption.AggregatedCostOperationGroup.getForBillingPeriodByManagementGroup", + "azure.mgmt.consumption.aio.operations.AggregatedCostOperations.get_for_billing_period_by_management_group": "Microsoft.Consumption.AggregatedCostOperationGroup.getForBillingPeriodByManagementGroup", + "azure.mgmt.consumption.operations.EventsOperations.list_by_billing_profile": "Microsoft.Consumption.EventsOperationGroup.listByBillingProfile", + "azure.mgmt.consumption.aio.operations.EventsOperations.list_by_billing_profile": "Microsoft.Consumption.EventsOperationGroup.listByBillingProfile", + "azure.mgmt.consumption.operations.EventsOperations.list_by_billing_account": "Microsoft.Consumption.EventsOperationGroup.listByBillingAccount", + "azure.mgmt.consumption.aio.operations.EventsOperations.list_by_billing_account": "Microsoft.Consumption.EventsOperationGroup.listByBillingAccount", + "azure.mgmt.consumption.operations.LotsOperations.list_by_billing_profile": "Microsoft.Consumption.LotsOperationGroup.listByBillingProfile", + "azure.mgmt.consumption.aio.operations.LotsOperations.list_by_billing_profile": "Microsoft.Consumption.LotsOperationGroup.listByBillingProfile", + "azure.mgmt.consumption.operations.LotsOperations.list_by_billing_account": "Microsoft.Consumption.LotsOperationGroup.listByBillingAccount", + "azure.mgmt.consumption.aio.operations.LotsOperations.list_by_billing_account": "Microsoft.Consumption.LotsOperationGroup.listByBillingAccount", + "azure.mgmt.consumption.operations.LotsOperations.list_by_customer": "Microsoft.Consumption.LotsOperationGroup.listByCustomer", + "azure.mgmt.consumption.aio.operations.LotsOperations.list_by_customer": "Microsoft.Consumption.LotsOperationGroup.listByCustomer" + }, + "CrossLanguageVersion": "4fbce2be986a" +} \ No newline at end of file diff --git a/sdk/consumption/azure-mgmt-consumption/azure/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore 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 fcba3ab9cc05..0e5913623c2c 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/__init__.py @@ -2,18 +2,24 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._consumption_management_client import ConsumptionManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ConsumptionManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -21,6 +27,6 @@ __all__ = [ "ConsumptionManagementClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_client.py similarity index 66% rename from sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py rename to sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_client.py index e4acefe4f418..d7509912a142 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_consumption_management_client.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_client.py @@ -2,19 +2,23 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +import sys +from typing import Any, Optional, TYPE_CHECKING, cast +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints -from . import models as _models from ._configuration import ConsumptionManagementClientConfiguration -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer from .operations import ( AggregatedCostOperations, BalancesOperations, @@ -35,21 +39,32 @@ UsageDetailsOperations, ) +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials import TokenCredential -class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class ConsumptionManagementClient: # pylint: disable=too-many-instance-attributes """Consumption management client provides access to consumption resources for Azure Enterprise Subscriptions. + :ivar operations: Operations operations + :vartype operations: azure.mgmt.consumption.operations.Operations + :ivar price_sheet: PriceSheetOperations operations + :vartype price_sheet: azure.mgmt.consumption.operations.PriceSheetOperations + :ivar budgets: BudgetsOperations operations + :vartype budgets: azure.mgmt.consumption.operations.BudgetsOperations + :ivar credits: CreditsOperations operations + :vartype credits: azure.mgmt.consumption.operations.CreditsOperations :ivar usage_details: UsageDetailsOperations operations :vartype usage_details: azure.mgmt.consumption.operations.UsageDetailsOperations :ivar marketplaces: MarketplacesOperations operations :vartype marketplaces: azure.mgmt.consumption.operations.MarketplacesOperations - :ivar budgets: BudgetsOperations operations - :vartype budgets: azure.mgmt.consumption.operations.BudgetsOperations :ivar tags: TagsOperations operations :vartype tags: azure.mgmt.consumption.operations.TagsOperations :ivar charges: ChargesOperations operations @@ -70,48 +85,82 @@ class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version :ivar reservation_transactions: ReservationTransactionsOperations operations :vartype reservation_transactions: azure.mgmt.consumption.operations.ReservationTransactionsOperations - :ivar price_sheet: PriceSheetOperations operations - :vartype price_sheet: azure.mgmt.consumption.operations.PriceSheetOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.consumption.operations.Operations :ivar aggregated_cost: AggregatedCostOperations operations :vartype aggregated_cost: azure.mgmt.consumption.operations.AggregatedCostOperations :ivar events: EventsOperations operations :vartype events: azure.mgmt.consumption.operations.EventsOperations :ivar lots: LotsOperations operations :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. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: Azure Subscription ID. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service host. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are "2024-08-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, credential: "TokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = ConsumptionManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + subscription_id=subscription_id, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs ) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, _endpoint), policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.credits = CreditsOperations(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) @@ -130,20 +179,17 @@ 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) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -156,15 +202,19 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() - def __enter__(self) -> "ConsumptionManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details) -> None: + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) 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 013feb87a864..b5a5112a1c25 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_configuration.py @@ -2,47 +2,52 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy 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 import AzureClouds from azure.core.credentials import TokenCredential -class ConsumptionManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ConsumptionManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for ConsumptionManagementClient. 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. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: Azure Subscription ID. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. 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. + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are "2024-08-01" + and None. Default value is None. If not set, the operation's default API version will be used. + 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: - super(ConsumptionManagementClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", "2021-10-01") + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,9 +56,12 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.credential = credential self.subscription_id = subscription_id + self.base_url = base_url + self.cloud_setting = cloud_setting 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.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -62,9 +70,9 @@ def _configure(self, **kwargs: Any) -> None: 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.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( 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 f99e77fef986..ea765788358a 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_patch.py @@ -1,31 +1,20 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + -# 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 + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/__init__.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/model_base.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/model_base.py new file mode 100644 index 000000000000..bd5b9caf1022 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/model_base.py @@ -0,0 +1,1755 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null + +from azure.core.rest import HttpResponse + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_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}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _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") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass: dict[str, typing.Any] = {} + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) + super().__init__(dict_to_pass) + + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + original_tsp_name: typing.Optional[str] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._deserializer = deserializer + self._original_tsp_name = original_tsp_name + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, + original_tsp_name: typing.Optional[str] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + deserializer=deserializer, + original_tsp_name=original_tsp_name, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/serialization.py similarity index 75% rename from sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py rename to sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/serialization.py index 2c170e28dbca..a088671e9c51 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_serialization.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -38,7 +20,17 @@ import re import sys import codecs -from typing import Optional, Union, AnyStr, IO, Mapping +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) try: from urllib import quote # type: ignore @@ -48,12 +40,18 @@ import isodate # type: ignore -from typing import Dict, Any, cast +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") +JSON = MutableMapping[str, Any] + class RawDeserializer: @@ -74,6 +72,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :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. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -95,7 +95,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -107,7 +107,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # 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 @@ -126,7 +126,9 @@ def _json_attemp(data): # 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("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -136,6 +138,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -153,13 +160,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -167,80 +167,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], 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 +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -287,25 +245,35 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): - """Compare objects by comparing all attributes.""" + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False - def __ne__(self, other): - """Compare objects by comparing all attributes.""" + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) - def __str__(self): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: cls._xml_map # type: ignore except AttributeError: @@ -314,7 +282,11 @@ def is_xml_model(cls): @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -322,8 +294,8 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -334,10 +306,17 @@ def serialize(self, keep_readonly=False, **kwargs): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -363,12 +342,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -378,25 +360,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls, data, content_type=None): + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -404,13 +392,15 @@ def from_dict(cls, data, key_extractors=None, content_type=None): and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -418,7 +408,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -426,21 +416,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -479,11 +473,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -518,7 +514,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -534,17 +530,20 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: dict[str, type] = 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): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object 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. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -570,17 +569,19 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + 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) + serialized |= target_obj.additional_properties continue try: @@ -602,7 +603,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): @@ -611,7 +612,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): 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 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 @@ -622,12 +624,11 @@ def _serialize(self, target_obj, data_type=None, **kwargs): 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) + local_node.text = 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 = {k: new_attr} _new_attr = new_attr _serialized = serialized @@ -636,28 +637,29 @@ def _serialize(self, target_obj, data_type=None, **kwargs): _serialized.update(_new_attr) # type: ignore _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise 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 + raise SerializationError(msg) from err + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object 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 + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -681,20 +683,22 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from 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 name: The name of the URL path parameter. + :param object 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 + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -703,30 +707,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + 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 name: The name of the query parameter. + :param object 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 + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ 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)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -736,19 +740,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + 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 name: The name of the header. + :param object 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 + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -757,35 +762,36 @@ def header(self, name, data, data_type, **kwargs): 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) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + 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 object 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. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") try: + if data is CoreNull: + return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if 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__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -795,12 +801,11 @@ def serialize_data(self, data, data_type, **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) + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -816,23 +821,33 @@ def serialize_basic(cls, data, data_type, **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 obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ 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 + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @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. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -846,8 +861,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -857,13 +871,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): 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 list data: 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'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -875,9 +889,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -913,16 +932,17 @@ def serialize_dict(self, attr, dict_type, **kwargs): :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 + :return: serialized dictionary """ 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: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -937,7 +957,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """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 @@ -945,6 +965,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -955,7 +976,7 @@ def serialize_object(self, attr, **kwargs): 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: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -969,7 +990,7 @@ def serialize_object(self, attr, **kwargs): 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): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1000,56 +1021,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: 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)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1057,11 +1083,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1071,30 +1098,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ 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.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1107,12 +1136,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1132,19 +1162,20 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """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 + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1152,16 +1183,17 @@ def serialize_unix(attr, **kwargs): 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.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1170,14 +1202,15 @@ def rest_key_extractor(attr, attr_desc, 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): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1191,7 +1224,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, 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:]) @@ -1199,17 +1231,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, 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.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ 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): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """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" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1242,11 +1286,11 @@ def _extract_name_from_internal_type(internal_type): 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) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1266,7 +1310,7 @@ def xml_key_extractor(attr, attr_desc, data): # 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) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1298,22 +1342,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + 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 - ) + # 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. + ) + 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: @@ -1321,7 +1364,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1330,9 +1373,9 @@ class Deserializer(object): 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}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1352,7 +1395,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: dict[str, type] = 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 @@ -1362,33 +1405,56 @@ def __init__(self, classes=None): # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """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. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """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. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: 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(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1405,15 +1471,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1442,10 +1508,9 @@ def _deserialize(self, target_obj, data): 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) + raise DeserializationError(msg) from err + 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: @@ -1471,22 +1536,24 @@ def _classify_target(self, target, data): 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. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify - return target, target.__class__.__name__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1496,12 +1563,14 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): 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/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1519,10 +1588,12 @@ def _unpack_content(raw_data, content_type=None): 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. + :param obj raw_data: Data to be processed. + :param str 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 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1539,31 +1610,42 @@ def _unpack_content(raw_data, content_type=None): 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"): + if isinstance(raw_data, (str, 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. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ 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")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + 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 + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1572,15 +1654,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """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. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1594,7 +1677,11 @@ def deserialize_data(self, data, data_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"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "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) @@ -1613,15 +1700,15 @@ def deserialize_data(self, data, data_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) + raise DeserializationError(msg) from err + 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. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1638,6 +1725,7 @@ def deserialize_dict(self, attr, dict_type): :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. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1648,20 +1736,21 @@ def deserialize_dict(self, attr, dict_type): 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): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :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): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1687,11 +1776,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """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 @@ -1699,8 +1787,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1710,24 +1799,27 @@ def deserialize_basic(self, attr, data_type): 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 + # 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 isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if 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 + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): @@ -1735,6 +1827,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1748,8 +1841,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1761,6 +1853,7 @@ def deserialize_enum(data, enum_obj): :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. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1769,12 +1862,11 @@ def deserialize_enum(data, enum_obj): 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: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1790,8 +1882,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1802,8 +1895,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1817,24 +1911,26 @@ 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. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1845,8 +1941,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1854,32 +1951,33 @@ def deserialize_duration(attr): 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 + raise DeserializationError(msg) from err + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :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) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1892,31 +1990,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :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)) + *parsed_date[:6], tzinfo=datetime.timezone(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 + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1943,9 +2042,8 @@ def deserialize_iso(attr): 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 + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1953,15 +2051,16 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) 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 + raise DeserializationError(msg) from err + 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 deleted file mode 100644 index 9aad73fc743e..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_vendor.py +++ /dev/null @@ -1,27 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py index 75a1436b862f..9ef7ae767063 100644 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/_version.py @@ -2,8 +2,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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "11.0.0b1" +VERSION = "11.0.0b2" 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 9cde86302a9b..98596ff49a10 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 @@ -2,15 +2,21 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._consumption_management_client import ConsumptionManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ConsumptionManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -18,6 +24,6 @@ __all__ = [ "ConsumptionManagementClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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/_client.py similarity index 66% rename from sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_consumption_management_client.py rename to sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/_client.py index bbfde391df8d..a464be22aa96 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/_client.py @@ -2,18 +2,22 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +import sys +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints -from .. import models as _models -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import ConsumptionManagementClientConfiguration from .operations import ( AggregatedCostOperations, @@ -35,21 +39,32 @@ UsageDetailsOperations, ) +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials_async import AsyncTokenCredential -class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes +class ConsumptionManagementClient: # pylint: disable=too-many-instance-attributes """Consumption management client provides access to consumption resources for Azure Enterprise Subscriptions. + :ivar operations: Operations operations + :vartype operations: azure.mgmt.consumption.aio.operations.Operations + :ivar price_sheet: PriceSheetOperations operations + :vartype price_sheet: azure.mgmt.consumption.aio.operations.PriceSheetOperations + :ivar budgets: BudgetsOperations operations + :vartype budgets: azure.mgmt.consumption.aio.operations.BudgetsOperations + :ivar credits: CreditsOperations operations + :vartype credits: azure.mgmt.consumption.aio.operations.CreditsOperations :ivar usage_details: UsageDetailsOperations operations :vartype usage_details: azure.mgmt.consumption.aio.operations.UsageDetailsOperations :ivar marketplaces: MarketplacesOperations operations :vartype marketplaces: azure.mgmt.consumption.aio.operations.MarketplacesOperations - :ivar budgets: BudgetsOperations operations - :vartype budgets: azure.mgmt.consumption.aio.operations.BudgetsOperations :ivar tags: TagsOperations operations :vartype tags: azure.mgmt.consumption.aio.operations.TagsOperations :ivar charges: ChargesOperations operations @@ -71,48 +86,84 @@ class ConsumptionManagementClient: # pylint: disable=client-accepts-api-version :ivar reservation_transactions: ReservationTransactionsOperations operations :vartype reservation_transactions: azure.mgmt.consumption.aio.operations.ReservationTransactionsOperations - :ivar price_sheet: PriceSheetOperations operations - :vartype price_sheet: azure.mgmt.consumption.aio.operations.PriceSheetOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.consumption.aio.operations.Operations :ivar aggregated_cost: AggregatedCostOperations operations :vartype aggregated_cost: azure.mgmt.consumption.aio.operations.AggregatedCostOperations :ivar events: EventsOperations operations :vartype events: azure.mgmt.consumption.aio.operations.EventsOperations :ivar lots: LotsOperations operations :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. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: Azure Subscription ID. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service host. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are "2024-08-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = ConsumptionManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + subscription_id=subscription_id, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs ) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, _endpoint), policies=_policies, **kwargs + ) + + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.budgets = BudgetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.credits = CreditsOperations(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) @@ -131,20 +182,19 @@ 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) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -157,15 +207,19 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncH """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "ConsumptionManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) 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 92d21cc93087..b2fe00c52a16 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 @@ -2,47 +2,52 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy 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 import AzureClouds from azure.core.credentials_async import AsyncTokenCredential -class ConsumptionManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ConsumptionManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for ConsumptionManagementClient. 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. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: Azure Subscription ID. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. 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. + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are "2024-08-01" + and None. Default value is None. If not set, the operation's default API version will be used. + 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: - super(ConsumptionManagementClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", "2021-10-01") + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,9 +56,12 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.credential = credential self.subscription_id = subscription_id + self.base_url = base_url + self.cloud_setting = cloud_setting 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.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -62,9 +70,9 @@ def _configure(self, **kwargs: Any) -> None: 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.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( 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 f99e77fef986..ea765788358a 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 @@ -1,31 +1,20 @@ # coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + -# 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 + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/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 33de5eb645bc..ef22c6aa0d68 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 @@ -2,36 +2,45 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._usage_details_operations import UsageDetailsOperations -from ._marketplaces_operations import MarketplacesOperations -from ._budgets_operations import BudgetsOperations -from ._tags_operations import TagsOperations -from ._charges_operations import ChargesOperations -from ._balances_operations import BalancesOperations -from ._reservations_summaries_operations import ReservationsSummariesOperations -from ._reservations_details_operations import ReservationsDetailsOperations -from ._reservation_recommendations_operations import ReservationRecommendationsOperations -from ._reservation_recommendation_details_operations import ReservationRecommendationDetailsOperations -from ._reservation_transactions_operations import ReservationTransactionsOperations -from ._price_sheet_operations import PriceSheetOperations -from ._operations import Operations -from ._aggregated_cost_operations import AggregatedCostOperations -from ._events_operations import EventsOperations -from ._lots_operations import LotsOperations -from ._credits_operations import CreditsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import PriceSheetOperations # type: ignore +from ._operations import BudgetsOperations # type: ignore +from ._operations import CreditsOperations # type: ignore +from ._operations import UsageDetailsOperations # type: ignore +from ._operations import MarketplacesOperations # type: ignore +from ._operations import TagsOperations # type: ignore +from ._operations import ChargesOperations # type: ignore +from ._operations import BalancesOperations # type: ignore +from ._operations import ReservationsSummariesOperations # type: ignore +from ._operations import ReservationsDetailsOperations # type: ignore +from ._operations import ReservationRecommendationsOperations # type: ignore +from ._operations import ReservationRecommendationDetailsOperations # type: ignore +from ._operations import ReservationTransactionsOperations # type: ignore +from ._operations import AggregatedCostOperations # type: ignore +from ._operations import EventsOperations # type: ignore +from ._operations import LotsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ + "Operations", + "PriceSheetOperations", + "BudgetsOperations", + "CreditsOperations", "UsageDetailsOperations", "MarketplacesOperations", - "BudgetsOperations", "TagsOperations", "ChargesOperations", "BalancesOperations", @@ -40,12 +49,9 @@ "ReservationRecommendationsOperations", "ReservationRecommendationDetailsOperations", "ReservationTransactionsOperations", - "PriceSheetOperations", - "Operations", "AggregatedCostOperations", "EventsOperations", "LotsOperations", - "CreditsOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _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 deleted file mode 100644 index 719fcf0fd3ef..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_aggregated_cost_operations.py +++ /dev/null @@ -1,192 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._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:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`aggregated_cost` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get_by_management_group( - 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. 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 - does not currently support 'ne', 'or', or 'not'. 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: ManagementGroupAggregatedCostResult or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - filter=filter, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } - - @distributed_trace_async - async def get_for_billing_period_by_management_group( - 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. Required. - :type management_group_id: str - :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) - :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index bec3e86e7d3d..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_balances_operations.py +++ /dev/null @@ -1,184 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._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:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`balances` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get_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. 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) - :rtype: ~azure.mgmt.consumption.models.Balance - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } - - @distributed_trace_async - async def get_for_billing_period_by_billing_account( - 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. Required. - :type billing_account_id: str - :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) - :rtype: ~azure.mgmt.consumption.models.Balance - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index eefdd10b3308..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_budgets_operations.py +++ /dev/null @@ -1,482 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._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:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`budgets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - 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 - '/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 - :keyword callable cls: A custom type or function that will be passed the direct response - :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: 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, - 304: ResourceNotModifiedError, - } - 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets"} - - @distributed_trace_async - 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 - '/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 - :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, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Budget", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} - - @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 - 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: ~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 - 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, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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) - - 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, - budget_name=budget_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.create_or_update.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize("Budget", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Budget", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # 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 - ) -> None: - """The operation to delete a budget. - - :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 - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - 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 deleted file mode 100644 index a5e80610b7c4..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_charges_operations.py +++ /dev/null @@ -1,154 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._charges_operations import 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 ChargesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`charges` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def list( - self, - scope: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - filter: Optional[str] = None, - apply: Optional[str] = None, - **kwargs: Any - ) -> _models.ChargesListResult: - """Lists the charges based for the defined scope. - - :param scope: The scope associated with charges operations. This includes - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' - for Department scope, and - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' - for EnrollmentAccount scope. For department and enrollment accounts, you can also add billing - period to the scope using '/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. - For e.g. to specify billing period at department scope use - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. - Also, Modern Commerce Account scopes are - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. Required. - :type scope: str - :param start_date: Start date. Default value is None. - :type start_date: str - :param end_date: End date. Default value is None. - :type end_date: str - :param filter: May be used to filter charges by properties/usageEnd (Utc time), - properties/usageStart (Utc time). The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. - It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where - key and value is separated by a colon (:). Default value is None. - :type filter: str - :param apply: May be used to group charges for billingAccount scope by - properties/billingProfileId, properties/invoiceSectionId, properties/customerId (specific for - Partner Led), or for billingProfile scope by properties/invoiceSectionId. Default value is - 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) - :rtype: ~azure.mgmt.consumption.models.ChargesListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - start_date=start_date, - end_date=end_date, - filter=filter, - apply=apply, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChargesListResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - 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 deleted file mode 100644 index e35c87cd3480..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_credits_operations.py +++ /dev/null @@ -1,122 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._credits_operations import build_get_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 CreditsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`credits` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, 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. Required. - :type billing_account_id: str - :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 None or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.CreditSummary or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index 91bc7ae68e49..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_events_operations.py +++ /dev/null @@ -1,254 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._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:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`events` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_billing_profile( - 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. Required. - :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. Required. - :type billing_profile_id: str - :param start_date: Start date. Required. - :type start_date: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - start_date=start_date, - end_date=end_date, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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.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. 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'. - 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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 deleted file mode 100644 index 300c7aafcca8..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_lots_operations.py +++ /dev/null @@ -1,347 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._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:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`lots` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_billing_profile( - 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. Required. - :type billing_account_id: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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.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. 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 - 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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.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. Required. - :type billing_account_id: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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 deleted file mode 100644 index 924441566518..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_marketplaces_operations.py +++ /dev/null @@ -1,177 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._marketplaces_operations import 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 MarketplacesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`marketplaces` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - scope: str, - filter: Optional[str] = None, - top: Optional[int] = None, - skiptoken: Optional[str] = None, - **kwargs: Any - ) -> 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. - - :param scope: The scope associated with marketplace operations. This includes - '/subscriptions/{subscriptionId}/' for subscription scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, - '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, - '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount - scope and '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management - Group scope. For subscription, billing account, department, enrollment account and - ManagementGroup, you can also add billing period to the scope using - '/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 - properties/instanceId. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not - currently support 'ne', 'or', or 'not'. Default value is None. - :type filter: str - :param top: May be used to limit the number of results to the most recent N marketplaces. - Default value is None. - :type top: int - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - 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 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: 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, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_request( - scope=scope, - filter=filter, - top=top, - skiptoken=skiptoken, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.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 715254cec870..3159d9b64592 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 @@ -1,15 +1,19 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from collections.abc import MutableMapping +import decimal +from io import IOBase +import json +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,25 +21,62 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request -from ...operations._operations import build_list_request +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_aggregated_cost_get_by_management_group_request, + build_aggregated_cost_get_for_billing_period_by_management_group_request, + build_balances_get_by_billing_account_request, + build_balances_get_for_billing_period_by_billing_account_request, + build_budgets_create_or_update_request, + build_budgets_delete_request, + build_budgets_get_request, + build_budgets_list_request, + build_charges_list_request, + build_credits_get_request, + build_events_list_by_billing_account_request, + build_events_list_by_billing_profile_request, + build_lots_list_by_billing_account_request, + build_lots_list_by_billing_profile_request, + build_lots_list_by_customer_request, + build_marketplaces_list_request, + build_operations_list_request, + build_price_sheet_download_by_billing_account_period_request, + build_price_sheet_get_by_billing_period_request, + build_price_sheet_get_request, + build_reservation_recommendation_details_get_request, + build_reservation_recommendations_list_request, + build_reservation_transactions_list_by_billing_profile_request, + build_reservation_transactions_list_request, + build_reservations_details_list_by_reservation_order_and_reservation_request, + build_reservations_details_list_by_reservation_order_request, + build_reservations_details_list_request, + build_reservations_summaries_list_by_reservation_order_and_reservation_request, + build_reservations_summaries_list_by_reservation_order_request, + build_reservations_summaries_list_request, + build_tags_get_request, + build_usage_details_list_request, +) +from .._configuration import ConsumptionManagementClientConfiguration -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +List = list class Operations: @@ -48,33 +89,742 @@ class Operations: :attr:`operations` attribute. """ - models = _models - def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: - """Lists all of the available consumption REST API operations. + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """List the operations for the provider. - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Operation or the result of cls(response) + :return: An iterator like instance of Operation :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 {}) + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Operation], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class PriceSheetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`price_sheet` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get_by_billing_period( + self, + billing_period_name: str, + *, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models.PriceSheetResult: + """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. Required. + :type billing_period_name: str + :keyword 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. + :paramtype expand: str + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :keyword top: May be used to limit the number of results to the top N results. Default value is + None. + :paramtype top: int + :return: PriceSheetResult. The PriceSheetResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.PriceSheetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) + + _request = build_price_sheet_get_by_billing_period_request( + billing_period_name=billing_period_name, + subscription_id=self._config.subscription_id, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PriceSheetResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get( + 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. + + :keyword 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. + :paramtype expand: str + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :keyword top: May be used to limit the number of results to the top N results. Default value is + None. + :paramtype top: int + :return: PriceSheetResult. The PriceSheetResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.PriceSheetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) + + _request = build_price_sheet_get_request( + subscription_id=self._config.subscription_id, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PriceSheetResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _download_by_billing_account_period_initial( # pylint: disable=name-too-long + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_price_sheet_download_by_billing_account_period_request( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_download_by_billing_account_period( + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatus]: + """Generates the pricesheet for the provided billing period asynchronously based on the enrollment + id. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: An instance of AsyncLROPoller that returns OperationStatus. The OperationStatus is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.consumption.models.OperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._download_by_billing_account_period_initial( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.OperationStatus, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.OperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class BudgetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`budgets` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + 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 fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) + + _request = build_budgets_get_request( + scope=scope, + budget_name=budget_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Budget, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @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 + 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 fully qualified Azure Resource manager identifier of the resource. 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: ~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 + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, scope: str, budget_name: str, parameters: JSON, *, 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 fully qualified Azure Resource manager identifier of the resource. 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: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + scope: str, + budget_name: str, + parameters: IO[bytes], + *, + 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 fully qualified Azure Resource manager identifier of the resource. 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[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget. The Budget is compatible with MutableMapping + :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, JSON, IO[bytes]], **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 fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :param parameters: Parameters supplied to the Create Budget operation. Is one of the following + types: Budget, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.consumption.models.Budget or JSON or IO[bytes] + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_budgets_create_or_update_request( + scope=scope, + budget_name=budget_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Budget, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, scope: str, budget_name: str, **kwargs: Any) -> None: + """The operation to delete a budget. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_budgets_delete_request( + scope=scope, + budget_name=budget_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list(self, scope: str, **kwargs: Any) -> AsyncItemPaged["_models.Budget"]: + """Lists all budgets for the defined scope. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :return: An iterator like instance of Budget + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Budget] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Budget]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,14 +835,18 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( - api_version=api_version, - template_url=self.list.metadata["url"], + _request = build_budgets_list_request( + scope=scope, + api_version=self._config.api_version, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -104,36 +858,2793 @@ def prepare_request(next_link=None): } ) _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 = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Budget], + deserialized.get("value", []), + ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.Consumption/operations"} + +class CreditsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`credits` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> Optional[_models.CreditSummary]: + """The credit summary by billingAccountId and billingProfileId. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :return: CreditSummary or None. The CreditSummary is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.CreditSummary or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Optional[_models.CreditSummary]] = kwargs.pop("cls", None) + + _request = build_credits_get_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CreditSummary, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class UsageDetailsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`usage_details` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + scope: str, + *, + expand: Optional[str] = None, + filter: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + metric: Optional[Union[str, _models.Metrictype]] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.UsageDetail"]: + """Lists the usage details for the defined scope. Usage details are available via this API only + for May 1, 2014 or later. + + **Note:Microsoft will be retiring the Consumption Usage Details API at some point in the + future. We do not recommend that you take a new dependency on this API. Please use the Cost + Details API instead. We will notify customers once a date for retirement has been + determined.For Learn more,see [Generate Cost Details Report - Create + Operation](https://learn.microsoft.com/en-us/rest/api/cost-management/generate-cost-details-report/create-operation?tabs=HTTP)**. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :keyword 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 + details. Default value is None. + :paramtype expand: str + :keyword filter: May be used to filter usageDetails by properties/resourceGroup, + properties/resourceName, properties/resourceId, properties/chargeType, + properties/reservationId, properties/publisherType or tags. The filter supports 'eq', 'lt', + 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is + a key value pair string where key and value is separated by a colon (:). PublisherType Filter + accepts two values azure and marketplace and it is currently supported for Web Direct Offer + Type. Default value is None. + :paramtype filter: str + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :keyword top: May be used to limit the number of results to the most recent N usageDetails. + Default value is None. + :paramtype top: int + :keyword metric: Allows to select different type of cost/usage records. Known values are: + "actualcost", "amortizedcost", and "usage". Default value is None. + :paramtype metric: str or ~azure.mgmt.consumption.models.Metrictype + :return: An iterator like instance of UsageDetail + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.UsageDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.UsageDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_usage_details_list_request( + scope=scope, + expand=expand, + filter=filter, + skiptoken=skiptoken, + top=top, + metric=metric, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.UsageDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class MarketplacesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`marketplaces` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + scope: str, + *, + filter: Optional[str] = None, + top: Optional[int] = None, + skiptoken: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_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. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :keyword filter: May be used to filter marketplaces by properties/usageEnd (Utc time), + properties/usageStart (Utc time), properties/resourceGroup, properties/instanceName or + properties/instanceId. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not + currently support 'ne', 'or', or 'not'. Default value is None. + :paramtype filter: str + :keyword top: May be used to limit the number of results to the most recent N marketplaces. + Default value is None. + :paramtype top: int + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :return: An iterator like instance of Marketplace + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.Marketplace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Marketplace]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_marketplaces_list_request( + scope=scope, + filter=filter, + top=top, + skiptoken=skiptoken, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Marketplace], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class TagsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`tags` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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]: + """Get all available tag keys for the defined scope. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :return: TagsResult or None. The TagsResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.TagsResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Optional[_models.TagsResult]] = kwargs.pop("cls", None) + + _request = build_tags_get_request( + scope=scope, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.TagsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ChargesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`charges` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list( + self, + scope: str, + *, + start_date: Optional[str] = None, + end_date: Optional[str] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + **kwargs: Any + ) -> _models.ChargesListResult: + """Lists the charges based for the defined scope. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :keyword start_date: Start date. Default value is None. + :paramtype start_date: str + :keyword end_date: End date. Default value is None. + :paramtype end_date: str + :keyword filter: May be used to filter charges by properties/usageEnd (Utc time), + properties/usageStart (Utc time). The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. + It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where + key and value is separated by a colon (:). Default value is None. + :paramtype filter: str + :keyword apply: May be used to group charges for billingAccount scope by + properties/billingProfileId, properties/invoiceSectionId, properties/customerId (specific for + Partner Led), or for billingProfile scope by properties/invoiceSectionId. Default value is + None. + :paramtype apply: str + :return: ChargesListResult. The ChargesListResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ChargesListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ChargesListResult] = kwargs.pop("cls", None) + + _request = build_charges_list_request( + scope=scope, + start_date=start_date, + end_date=end_date, + filter=filter, + apply=apply, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ChargesListResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class BalancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`balances` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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: + """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. Required. + :type billing_account_id: str + :return: Balance. The Balance is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Balance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) + + _request = build_balances_get_by_billing_account_request( + billing_account_id=billing_account_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Balance, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_for_billing_period_by_billing_account( # pylint: disable=name-too-long + 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. Required. + :type billing_account_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: Balance. The Balance is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Balance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) + + _request = build_balances_get_for_billing_period_by_billing_account_request( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Balance, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ReservationsSummariesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`reservations_summaries` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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], + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.ReservationSummary"]: + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 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. Required. + :type reservation_order_id: str + :keyword grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. + :paramtype grain: str or ~azure.mgmt.consumption.models.Datagrain + :keyword 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. + :paramtype filter: str + :return: An iterator like instance of ReservationSummary + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_summaries_list_by_reservation_order_request( + reservation_order_id=reservation_order_id, + grain=grain, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long + self, + reservation_order_id: str, + reservation_id: str, + *, + grain: Union[str, _models.Datagrain], + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.ReservationSummary"]: + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 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. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation. Required. + :type reservation_id: str + :keyword grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. + :paramtype grain: str or ~azure.mgmt.consumption.models.Datagrain + :keyword 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. + :paramtype filter: str + :return: An iterator like instance of ReservationSummary + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_summaries_list_by_reservation_order_and_reservation_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + grain=grain, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, + resource_scope: str, + *, + 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 + ) -> AsyncItemPaged["_models.ReservationSummary"]: + """Lists the reservations summaries for the defined scope daily or monthly grain. Note: ARM has a + payload size limit of 12MB, so currently callers get 400 when the response size exceeds the ARM + limit. In such cases, API call should be made with smaller date ranges. + + :param resource_scope: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_scope: str + :keyword grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. + :paramtype grain: str or ~azure.mgmt.consumption.models.Datagrain + :keyword start_date: Start date. Only applicable when querying with billing profile. Default + value is None. + :paramtype start_date: str + :keyword end_date: End date. Only applicable when querying with billing profile. Default value + is None. + :paramtype end_date: str + :keyword filter: Required only for daily grain. The properties/UsageDate for start date and end + date. The filter supports 'le' and 'ge'. Not applicable when querying with billing profile. + Default value is None. + :paramtype filter: str + :keyword reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also + provided. Filter to a specific reservation. Default value is None. + :paramtype reservation_id: str + :keyword reservation_order_id: Reservation Order Id GUID. Required if reservationId is + provided. Filter to a specific reservation order. Default value is None. + :paramtype reservation_order_id: str + :return: An iterator like instance of ReservationSummary + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_summaries_list_request( + resource_scope=resource_scope, + grain=grain, + start_date=start_date, + end_date=end_date, + filter=filter, + reservation_id=reservation_id, + reservation_order_id=reservation_order_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class ReservationsDetailsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`reservations_details` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> AsyncItemPaged["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :keyword filter: Filter reservation details by date range. The properties/UsageDate for start + date and end date. The filter supports 'le' and 'ge'. Required. + :paramtype filter: str + :return: An iterator like instance of ReservationDetail + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_details_list_by_reservation_order_request( + reservation_order_id=reservation_order_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long + self, reservation_order_id: str, reservation_id: str, *, filter: str, **kwargs: Any + ) -> AsyncItemPaged["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation. Required. + :type reservation_id: str + :keyword filter: Filter reservation details by date range. The properties/UsageDate for start + date and end date. The filter supports 'le' and 'ge'. Required. + :paramtype filter: str + :return: An iterator like instance of ReservationDetail + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_details_list_by_reservation_order_and_reservation_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, + resource_scope: str, + *, + 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 + ) -> AsyncItemPaged["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + :param resource_scope: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_scope: str + :keyword start_date: Start date. Only applicable when querying with billing profile. Default + value is None. + :paramtype start_date: str + :keyword end_date: End date. Only applicable when querying with billing profile. Default value + is None. + :paramtype end_date: str + :keyword filter: Filter reservation details by date range. The properties/UsageDate for start + date and end date. The filter supports 'le' and 'ge'. Not applicable when querying with + billing profile. Default value is None. + :paramtype filter: str + :keyword reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also + provided. Filter to a specific reservation. Default value is None. + :paramtype reservation_id: str + :keyword reservation_order_id: Reservation Order Id GUID. Required if reservationId is + provided. Filter to a specific reservation order. Default value is None. + :paramtype reservation_order_id: str + :return: An iterator like instance of ReservationDetail + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_details_list_request( + resource_scope=resource_scope, + start_date=start_date, + end_date=end_date, + filter=filter, + reservation_id=reservation_id, + reservation_order_id=reservation_order_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class ReservationRecommendationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`reservation_recommendations` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> AsyncItemPaged["_models.ReservationRecommendation"]: + """List of recommendations for purchasing reserved instances. + + :param resource_scope: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_scope: str + :keyword filter: May be used to filter reservationRecommendations by: properties/scope with + allowed values ['Single', 'Shared'] and default value 'Single'; properties/resourceType with + allowed values ['VirtualMachines', 'SQLDatabases', 'PostgreSQL', 'ManagedDisk', 'MySQL', + 'RedHat', 'MariaDB', 'RedisCache', 'CosmosDB', 'SqlDataWarehouse', 'SUSELinux', 'AppService', + 'BlockBlob', 'AzureDataExplorer', 'VMwareCloudSimple'] and default value 'VirtualMachines'; and + properties/lookBackPeriod with allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and + default value 'Last7Days'. Default value is None. + :paramtype filter: str + :return: An iterator like instance of ReservationRecommendation + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationRecommendation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationRecommendation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservation_recommendations_list_request( + resource_scope=resource_scope, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationRecommendation], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class ReservationRecommendationDetailsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`reservation_recommendation_details` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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], + region: str, + term: Union[str, _models.Term], + look_back_period: Union[str, _models.LookBackPeriod], + product: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Optional[_models.ReservationRecommendationDetailsModel]: + """Details of a reservation recommendation for what-if analysis of reserved instances. + + :param resource_scope: The scope associated with reservation recommendation details operations. + This includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/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. Required. + :type resource_scope: str + :keyword scope: Scope of the reservation. Known values are: "Single" and "Shared". Required. + :paramtype scope: str or ~azure.mgmt.consumption.models.Scope + :keyword region: Used to select the region the recommendation should be generated for. + Required. + :paramtype region: str + :keyword term: Specify length of reservation recommendation term. Known values are: "P1M", + "P1Y", and "P3Y". Required. + :paramtype term: str or ~azure.mgmt.consumption.models.Term + :keyword look_back_period: Filter the time period on which reservation recommendation results + are based. Known values are: "Last7Days", "Last30Days", and "Last60Days". Required. + :paramtype look_back_period: str or ~azure.mgmt.consumption.models.LookBackPeriod + :keyword 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. + :paramtype product: str + :keyword filter: Used to filter reservation recommendation details by: + properties/subscriptionId can be specified for billing account and billing profile paths. + Default value is None. + :paramtype filter: str + :return: ReservationRecommendationDetailsModel or None. The + ReservationRecommendationDetailsModel is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] = kwargs.pop("cls", None) + + _request = build_reservation_recommendation_details_get_request( + resource_scope=resource_scope, + scope=scope, + region=region, + term=term, + look_back_period=look_back_period, + product=product, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.HighCasedErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ReservationRecommendationDetailsModel, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ReservationTransactionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`reservation_transactions` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + billing_account_id: str, + *, + filter: Optional[str] = None, + use_markup_if_partner: Optional[bool] = None, + preview_markup_percentage: Optional[decimal.Decimal] = None, + **kwargs: Any + ) -> AsyncItemPaged["_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. Note: ARM has a payload size limit of 12MB, so currently callers get 400 when the + response size exceeds the ARM limit. In such cases, API call should be made with smaller date + ranges. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :keyword filter: Filter reservation transactions by date range. The properties/EventDate for + 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. + :paramtype filter: str + :keyword use_markup_if_partner: Applies mark up to the transactions if the caller is a partner. + Default value is None. + :paramtype use_markup_if_partner: bool + :keyword preview_markup_percentage: Preview markup percentage to be applied. Default value is + None. + :paramtype preview_markup_percentage: ~decimal.Decimal + :return: An iterator like instance of ReservationTransaction + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationTransaction]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservation_transactions_list_request( + billing_account_id=billing_account_id, + filter=filter, + use_markup_if_partner=use_markup_if_partner, + preview_markup_percentage=preview_markup_percentage, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationTransaction], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_billing_profile( + self, billing_account_id: str, billing_profile_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_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. Note: ARM + has a payload size limit of 12MB, so currently callers get 400 when the response size exceeds + the ARM limit. In such cases, API call should be made with smaller date ranges. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :keyword filter: Filter reservation transactions by date range. The properties/EventDate for + 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. + :paramtype filter: str + :return: An iterator like instance of ModernReservationTransaction + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.ModernReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ModernReservationTransaction]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservation_transactions_list_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ModernReservationTransaction], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class AggregatedCostOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`aggregated_cost` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> _models.ManagementGroupAggregatedCostResult: + """Provides the aggregate cost of a management group and all child management groups by current + billing period. + + :param management_group_id: Order Id of the reservation. Required. + :type management_group_id: str + :keyword 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. + :paramtype filter: str + :return: ManagementGroupAggregatedCostResult. The ManagementGroupAggregatedCostResult is + compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) + + _request = build_aggregated_cost_get_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupAggregatedCostResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_for_billing_period_by_management_group( # pylint: disable=name-too-long + 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: Order Id of the reservation. Required. + :type management_group_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: ManagementGroupAggregatedCostResult. The ManagementGroupAggregatedCostResult is + compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) + + _request = build_aggregated_cost_get_for_billing_period_by_management_group_request( + management_group_id=management_group_id, + billing_period_name=billing_period_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupAggregatedCostResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class EventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`events` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> AsyncItemPaged["_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. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :keyword start_date: Start date. Required. + :paramtype start_date: str + :keyword end_date: End date. Required. + :paramtype end_date: str + :return: An iterator like instance of EventSummary + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.EventSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EventSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_events_list_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + start_date=start_date, + end_date=end_date, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.EventSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_billing_account( + self, billing_account_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_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. Required. + :type billing_account_id: str + :keyword 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'. + Tag filter is a key value pair string where key and value is separated by a colon (:). Default + value is None. + :paramtype filter: str + :return: An iterator like instance of EventSummary + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.EventSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EventSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_events_list_by_billing_account_request( + billing_account_id=billing_account_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.EventSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class LotsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s + :attr:`lots` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> AsyncItemPaged["_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. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :return: An iterator like instance of LotSummary + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.LotSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_lots_list_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.LotSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_billing_account( + self, billing_account_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_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. Required. + :type billing_account_id: str + :keyword 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 filter is a key value pair string where key and value is separated by a colon (:). Default + value is None. + :paramtype filter: str + :return: An iterator like instance of LotSummary + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.LotSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_lots_list_by_billing_account_request( + billing_account_id=billing_account_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.LotSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_customer( + self, billing_account_id: str, customer_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_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. Required. + :type billing_account_id: str + :param customer_id: Customer ID. Required. + :type customer_id: str + :keyword 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. + :paramtype filter: str + :return: An iterator like instance of LotSummary + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.LotSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_lots_list_by_customer_request( + billing_account_id=billing_account_id, + customer_id=customer_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.LotSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) 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 f7dd32510333..ea765788358a 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 @@ -1,14 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): 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 deleted file mode 100644 index 4bb0b620ad7f..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_price_sheet_operations.py +++ /dev/null @@ -1,210 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._price_sheet_operations import build_get_by_billing_period_request, build_get_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 PriceSheetOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`price_sheet` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, 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. - - :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. - :type expand: str - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - value is None. - :type skiptoken: str - :param top: May be used to limit the number of results to the top N results. Default value is - 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) - :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - expand=expand, - skiptoken=skiptoken, - top=top, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PriceSheetResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} - - @distributed_trace_async - async def get_by_billing_period( - self, - billing_period_name: str, - expand: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> _models.PriceSheetResult: - """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. 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. - :type expand: str - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - value is None. - :type skiptoken: str - :param top: May be used to limit the number of results to the top N results. Default value is - 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) - :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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( - billing_period_name=billing_period_name, - subscription_id=self._config.subscription_id, - expand=expand, - skiptoken=skiptoken, - top=top, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index dd832048dc3e..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendation_details_operations.py +++ /dev/null @@ -1,148 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._reservation_recommendation_details_operations import build_get_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 ReservationRecommendationDetailsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`reservation_recommendation_details` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, - resource_scope: str, - scope: Union[str, _models.Scope], - region: str, - term: Union[str, _models.Term], - look_back_period: Union[str, _models.LookBackPeriod], - product: str, - **kwargs: Any - ) -> Optional[_models.ReservationRecommendationDetailsModel]: - """Details of a reservation recommendation for what-if analysis of reserved instances. - - :param resource_scope: The scope associated with reservation recommendation details operations. - This includes '/subscriptions/{subscriptionId}/' for subscription scope, - '/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. Required. - :type resource_scope: str - :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. Required. - :type region: str - :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. 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 None or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - scope=scope, - region=region, - term=term, - look_back_period=look_back_period, - product=product, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.HighCasedErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - 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 deleted file mode 100644 index b23a984c7447..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_recommendations_operations.py +++ /dev/null @@ -1,160 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._reservation_recommendations_operations import 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 ReservationRecommendationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`reservation_recommendations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - 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 - includes '/subscriptions/{subscriptionId}/' for subscription scope, - '/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. 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 - allowed values ['VirtualMachines', 'SQLDatabases', 'PostgreSQL', 'ManagedDisk', 'MySQL', - 'RedHat', 'MariaDB', 'RedisCache', 'CosmosDB', 'SqlDataWarehouse', 'SUSELinux', 'AppService', - 'BlockBlob', 'AzureDataExplorer', 'VMwareCloudSimple'] and default value 'VirtualMachines'; and - properties/lookBackPeriod with allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and - 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 ReservationRecommendation or the result of - cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{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 deleted file mode 100644 index 15671e3cf4a9..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservation_transactions_operations.py +++ /dev/null @@ -1,264 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._reservation_transactions_operations import build_list_by_billing_profile_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 ReservationTransactionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`reservation_transactions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - 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'. 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 ReservationTransaction or the result of - cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/providers/Microsoft.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.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. 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'. 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 ModernReservationTransaction or the result of - cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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 deleted file mode 100644 index cb74a06054b8..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_details_operations.py +++ /dev/null @@ -1,376 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._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:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`reservations_details` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_reservation_order( - 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. 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'. 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 ReservationDetail or the result of cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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.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. Required. - :type reservation_order_id: str - :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'. 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 ReservationDetail or the result of cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_reservation_order_and_reservation.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails" - } - - @distributed_trace - def list( - self, - resource_scope: str, - 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.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). Required. - :type resource_scope: str - :param start_date: Start date. Only applicable when querying with billing profile. Default - value is None. - :type start_date: str - :param end_date: End date. Only applicable when querying with billing profile. Default value is - None. - :type end_date: str - :param filter: Filter reservation details by date range. The properties/UsageDate for start - date and end date. The filter supports 'le' and 'ge'. Not applicable when querying with - billing profile. Default value is None. - :type filter: str - :param reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also provided. - Filter to a specific reservation. Default value is None. - :type reservation_id: str - :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. - 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 ReservationDetail or the result of cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=self.list.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{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 deleted file mode 100644 index 2c5bb97e1b10..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_reservations_summaries_operations.py +++ /dev/null @@ -1,389 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._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:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`reservations_summaries` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_reservation_order( - self, - reservation_order_id: str, - grain: Union[str, _models.Datagrain], - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :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 ReservationSummary or the result of cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - grain=grain, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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], - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation. Required. - :type reservation_id: str - :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 ReservationSummary or the result of cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - grain=grain, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_by_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], - 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.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). Required. - :type resource_scope: str - :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. - :type start_date: str - :param end_date: End date. Only applicable when querying with billing profile. Default value is - None. - :type end_date: str - :param filter: Required only for daily grain. The properties/UsageDate for start date and end - date. The filter supports 'le' and 'ge'. Not applicable when querying with billing profile. - Default value is None. - :type filter: str - :param reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also provided. - Filter to a specific reservation. Default value is None. - :type reservation_id: str - :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. - 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 ReservationSummary or the result of cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - grain=grain, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=self.list.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{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 deleted file mode 100644 index ec7c05804fe9..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_tags_operations.py +++ /dev/null @@ -1,124 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._tags_operations import build_get_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 TagsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`tags` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get(self, 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 - '/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 and - '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group - scope.. Required. - :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: TagsResult or None or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.TagsResult or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("TagsResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - 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 deleted file mode 100644 index 9b7ee901cf4c..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_usage_details_operations.py +++ /dev/null @@ -1,198 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._usage_details_operations import 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 UsageDetailsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.aio.ConsumptionManagementClient`'s - :attr:`usage_details` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - scope: str, - expand: Optional[str] = None, - filter: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - metric: Optional[Union[str, _models.Metrictype]] = None, - **kwargs: Any - ) -> 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. - - :param scope: The scope associated with usage details operations. This includes - '/subscriptions/{subscriptionId}/' for subscription scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, - '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, - '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount - scope and '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management - Group scope. For subscription, billing account, department, enrollment account and management - group, you can also add billing period to the scope using - '/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}'. - Also, Modern Commerce Account scopes are - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. Required. - :type scope: str - :param 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 - details. Default value is None. - :type expand: str - :param filter: May be used to filter usageDetails by properties/resourceGroup, - properties/resourceName, properties/resourceId, properties/chargeType, - properties/reservationId, properties/publisherType or tags. The filter supports 'eq', 'lt', - 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is - a key value pair string where key and value is separated by a colon (:). PublisherType Filter - accepts two values azure and marketplace and it is currently supported for Web Direct Offer - Type. Default value is None. - :type filter: str - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - value is None. - :type skiptoken: str - :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. 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 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: 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, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_request( - scope=scope, - expand=expand, - filter=filter, - skiptoken=skiptoken, - top=top, - metric=metric, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.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 134b6775b069..8258fdd112f6 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 @@ -2,196 +2,231 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models_py3 import Amount -from ._models_py3 import AmountWithExchangeRate -from ._models_py3 import Balance -from ._models_py3 import BalancePropertiesAdjustmentDetailsItem -from ._models_py3 import BalancePropertiesNewPurchasesDetailsItem -from ._models_py3 import Budget -from ._models_py3 import BudgetComparisonExpression -from ._models_py3 import BudgetFilter -from ._models_py3 import BudgetFilterProperties -from ._models_py3 import BudgetTimePeriod -from ._models_py3 import BudgetsListResult -from ._models_py3 import ChargeSummary -from ._models_py3 import ChargesListResult -from ._models_py3 import CreditBalanceSummary -from ._models_py3 import CreditSummary -from ._models_py3 import CurrentSpend -from ._models_py3 import DownloadProperties -from ._models_py3 import ErrorDetails -from ._models_py3 import ErrorResponse -from ._models_py3 import EventSummary -from ._models_py3 import Events -from ._models_py3 import ForecastSpend -from ._models_py3 import HighCasedErrorDetails -from ._models_py3 import HighCasedErrorResponse -from ._models_py3 import LegacyChargeSummary -from ._models_py3 import LegacyReservationRecommendation -from ._models_py3 import LegacyReservationRecommendationProperties -from ._models_py3 import LegacyReservationTransaction -from ._models_py3 import LegacySharedScopeReservationRecommendationProperties -from ._models_py3 import LegacySingleScopeReservationRecommendationProperties -from ._models_py3 import LegacyUsageDetail -from ._models_py3 import LotSummary -from ._models_py3 import Lots -from ._models_py3 import ManagementGroupAggregatedCostResult -from ._models_py3 import Marketplace -from ._models_py3 import MarketplacesListResult -from ._models_py3 import MeterDetails -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 -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import PriceSheetProperties -from ._models_py3 import PriceSheetResult -from ._models_py3 import ProxyResource -from ._models_py3 import Reseller -from ._models_py3 import ReservationDetail -from ._models_py3 import ReservationDetailsListResult -from ._models_py3 import ReservationRecommendation -from ._models_py3 import ReservationRecommendationDetailsCalculatedSavingsProperties -from ._models_py3 import ReservationRecommendationDetailsModel -from ._models_py3 import ReservationRecommendationDetailsResourceProperties -from ._models_py3 import ReservationRecommendationDetailsSavingsProperties -from ._models_py3 import ReservationRecommendationDetailsUsageProperties -from ._models_py3 import ReservationRecommendationsListResult -from ._models_py3 import ReservationSummariesListResult -from ._models_py3 import ReservationSummary -from ._models_py3 import ReservationTransaction -from ._models_py3 import ReservationTransactionResource -from ._models_py3 import ReservationTransactionsListResult -from ._models_py3 import Resource -from ._models_py3 import ResourceAttributes -from ._models_py3 import SkuProperty -from ._models_py3 import Tag -from ._models_py3 import TagsResult -from ._models_py3 import UsageDetail -from ._models_py3 import UsageDetailsListResult +from typing import TYPE_CHECKING -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 +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + Amount, + AmountWithExchangeRate, + Balance, + BalanceProperties, + BalancePropertiesAdjustmentDetailsItem, + BalancePropertiesNewPurchasesDetailsItem, + Budget, + BudgetComparisonExpression, + BudgetFilter, + BudgetFilterProperties, + BudgetProperties, + BudgetTimePeriod, + ChargeSummary, + ChargesListResult, + CreditBalanceSummary, + CreditSummary, + CreditSummaryProperties, + CurrentSpend, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + EventProperties, + EventSummary, + ExtensionResource, + ForecastSpend, + HighCasedErrorDetails, + HighCasedErrorResponse, + LegacyChargeSummary, + LegacyChargeSummaryProperties, + LegacyReservationRecommendation, + LegacyReservationRecommendationProperties, + LegacyReservationTransactionProperties, + LegacySharedScopeReservationRecommendationProperties, + LegacySingleScopeReservationRecommendationProperties, + LegacyUsageDetail, + LegacyUsageDetailProperties, + LotProperties, + LotSummary, + ManagementGroupAggregatedCostProperties, + ManagementGroupAggregatedCostResult, + Marketplace, + MarketplaceProperties, + MeterDetails, + MeterDetailsResponse, + ModernChargeSummary, + ModernChargeSummaryProperties, + ModernReservationRecommendation, + ModernReservationRecommendationProperties, + ModernReservationTransaction, + ModernReservationTransactionProperties, + ModernSharedScopeReservationRecommendationProperties, + ModernSingleScopeReservationRecommendationProperties, + ModernUsageDetail, + ModernUsageDetailProperties, + Notification, + Operation, + OperationDisplay, + OperationStatus, + PriceSheetModel, + PriceSheetProperties, + PriceSheetResult, + PricesheetDownloadProperties, + ProxyResource, + Reseller, + ReservationDetail, + ReservationDetailProperties, + ReservationRecommendation, + ReservationRecommendationDetailsCalculatedSavingsProperties, + ReservationRecommendationDetailsModel, + ReservationRecommendationDetailsProperties, + ReservationRecommendationDetailsResourceProperties, + ReservationRecommendationDetailsSavingsProperties, + ReservationRecommendationDetailsUsageProperties, + ReservationSummary, + ReservationSummaryProperties, + ReservationTransaction, + Resource, + SavingsPlan, + SkuProperty, + SystemData, + Tag, + TagProperties, + TagsResult, + UsageDetail, +) + +from ._enums import ( # type: ignore + BillingFrequency, + BudgetOperatorType, + CategoryType, + ChargeSummaryKind, + CreatedByType, + CultureCode, + Datagrain, + EventType, + LookBackPeriod, + LotSource, + Metrictype, + OperationStatusType, + OperatorType, + OrganizationType, + PricingModelType, + ReservationRecommendationKind, + Scope, + Status, + Term, + ThresholdType, + TimeGrainType, + UsageDetailsKind, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "Amount", "AmountWithExchangeRate", "Balance", + "BalanceProperties", "BalancePropertiesAdjustmentDetailsItem", "BalancePropertiesNewPurchasesDetailsItem", "Budget", "BudgetComparisonExpression", "BudgetFilter", "BudgetFilterProperties", + "BudgetProperties", "BudgetTimePeriod", - "BudgetsListResult", "ChargeSummary", "ChargesListResult", "CreditBalanceSummary", "CreditSummary", + "CreditSummaryProperties", "CurrentSpend", - "DownloadProperties", - "ErrorDetails", + "ErrorAdditionalInfo", + "ErrorDetail", "ErrorResponse", + "EventProperties", "EventSummary", - "Events", + "ExtensionResource", "ForecastSpend", "HighCasedErrorDetails", "HighCasedErrorResponse", "LegacyChargeSummary", + "LegacyChargeSummaryProperties", "LegacyReservationRecommendation", "LegacyReservationRecommendationProperties", - "LegacyReservationTransaction", + "LegacyReservationTransactionProperties", "LegacySharedScopeReservationRecommendationProperties", "LegacySingleScopeReservationRecommendationProperties", "LegacyUsageDetail", + "LegacyUsageDetailProperties", + "LotProperties", "LotSummary", - "Lots", + "ManagementGroupAggregatedCostProperties", "ManagementGroupAggregatedCostResult", "Marketplace", - "MarketplacesListResult", + "MarketplaceProperties", "MeterDetails", "MeterDetailsResponse", "ModernChargeSummary", + "ModernChargeSummaryProperties", "ModernReservationRecommendation", "ModernReservationRecommendationProperties", "ModernReservationTransaction", - "ModernReservationTransactionsListResult", + "ModernReservationTransactionProperties", "ModernSharedScopeReservationRecommendationProperties", "ModernSingleScopeReservationRecommendationProperties", "ModernUsageDetail", + "ModernUsageDetailProperties", "Notification", "Operation", "OperationDisplay", - "OperationListResult", + "OperationStatus", + "PriceSheetModel", "PriceSheetProperties", "PriceSheetResult", + "PricesheetDownloadProperties", "ProxyResource", "Reseller", "ReservationDetail", - "ReservationDetailsListResult", + "ReservationDetailProperties", "ReservationRecommendation", "ReservationRecommendationDetailsCalculatedSavingsProperties", "ReservationRecommendationDetailsModel", + "ReservationRecommendationDetailsProperties", "ReservationRecommendationDetailsResourceProperties", "ReservationRecommendationDetailsSavingsProperties", "ReservationRecommendationDetailsUsageProperties", - "ReservationRecommendationsListResult", - "ReservationSummariesListResult", "ReservationSummary", + "ReservationSummaryProperties", "ReservationTransaction", - "ReservationTransactionResource", - "ReservationTransactionsListResult", "Resource", - "ResourceAttributes", + "SavingsPlan", "SkuProperty", + "SystemData", "Tag", + "TagProperties", "TagsResult", "UsageDetail", - "UsageDetailsListResult", "BillingFrequency", "BudgetOperatorType", "CategoryType", "ChargeSummaryKind", + "CreatedByType", "CultureCode", "Datagrain", "EventType", "LookBackPeriod", "LotSource", "Metrictype", + "OperationStatusType", "OperatorType", + "OrganizationType", "PricingModelType", "ReservationRecommendationKind", "Scope", @@ -201,5 +236,5 @@ "TimeGrainType", "UsageDetailsKind", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _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/_enums.py similarity index 56% rename from sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_consumption_management_client_enums.py rename to sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_enums.py index ecb66e0217dd..d27f5c882e13 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/_enums.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -14,172 +14,259 @@ class BillingFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The billing frequency.""" MONTH = "Month" + """MONTH.""" QUARTER = "Quarter" + """QUARTER.""" YEAR = "Year" + """YEAR.""" class BudgetOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The operator to use for comparison.""" IN = "In" + """IN.""" class CategoryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The category of the budget, whether the budget tracks cost or usage.""" COST = "Cost" + """COST.""" class ChargeSummaryKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the kind of charge summary.""" LEGACY = "legacy" + """LEGACY.""" MODERN = "modern" + """MODERN.""" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of entity that created the resource.""" + + USER = "User" + """The entity was created by a user.""" + APPLICATION = "Application" + """The entity was created by an application.""" + MANAGED_IDENTITY = "ManagedIdentity" + """The entity was created by a managed identity.""" + KEY = "Key" + """The entity was created by a key.""" class CultureCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Language in which the recipient will receive the notification.""" EN_US = "en-us" + """EN_US.""" JA_JP = "ja-jp" + """JA_JP.""" ZH_CN = "zh-cn" + """ZH_CN.""" DE_DE = "de-de" + """DE_DE.""" ES_ES = "es-es" + """ES_ES.""" FR_FR = "fr-fr" + """FR_FR.""" IT_IT = "it-it" + """IT_IT.""" KO_KR = "ko-kr" + """KO_KR.""" PT_BR = "pt-br" + """PT_BR.""" RU_RU = "ru-ru" + """RU_RU.""" ZH_TW = "zh-tw" + """ZH_TW.""" CS_CZ = "cs-cz" + """CS_CZ.""" PL_PL = "pl-pl" + """PL_PL.""" TR_TR = "tr-tr" + """TR_TR.""" DA_DK = "da-dk" + """DA_DK.""" EN_GB = "en-gb" + """EN_GB.""" HU_HU = "hu-hu" + """HU_HU.""" NB_NO = "nb-no" + """NB_NO.""" NL_NL = "nl-nl" + """NL_NL.""" PT_PT = "pt-pt" + """PT_PT.""" SV_SE = "sv-se" + """SV_SE.""" class Datagrain(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Datagrain.""" + """Type of Datagrain.""" - #: Daily grain of data DAILY_GRAIN = "daily" - #: Monthly grain of data + """Daily grain of data.""" MONTHLY_GRAIN = "monthly" + """Monthly grain of data.""" class EventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Identifies the type of the event.""" SETTLED_CHARGES = "SettledCharges" + """SETTLED_CHARGES.""" PENDING_CHARGES = "PendingCharges" + """PENDING_CHARGES.""" PENDING_ADJUSTMENTS = "PendingAdjustments" + """PENDING_ADJUSTMENTS.""" PENDING_NEW_CREDIT = "PendingNewCredit" + """PENDING_NEW_CREDIT.""" PENDING_EXPIRED_CREDIT = "PendingExpiredCredit" + """PENDING_EXPIRED_CREDIT.""" UN_KNOWN = "UnKnown" + """UN_KNOWN.""" NEW_CREDIT = "NewCredit" + """NEW_CREDIT.""" CREDIT_EXPIRED = "CreditExpired" + """CREDIT_EXPIRED.""" class LookBackPeriod(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """LookBackPeriod.""" + """Type of LookBackPeriod.""" - #: Use 7 days of data for recommendations LAST07_DAYS = "Last7Days" - #: Use 30 days of data for recommendations + """Use 7 days of data for recommendations.""" LAST30_DAYS = "Last30Days" - #: Use 60 days of data for recommendations + """Use 30 days of data for recommendations.""" LAST60_DAYS = "Last60Days" + """Use 60 days of data for recommendations.""" class LotSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The source of the lot.""" PURCHASED_CREDIT = "PurchasedCredit" + """PURCHASED_CREDIT.""" PROMOTIONAL_CREDIT = "PromotionalCredit" + """PROMOTIONAL_CREDIT.""" CONSUMPTION_COMMITMENT = "ConsumptionCommitment" + """CONSUMPTION_COMMITMENT.""" class Metrictype(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Metrictype.""" + """Type of Metrictype.""" - #: Actual cost data. ACTUAL_COST_METRIC_TYPE = "actualcost" - #: Amortized cost data. + """Actual cost data.""" AMORTIZED_COST_METRIC_TYPE = "amortizedcost" - #: Usage data. + """Amortized cost data.""" USAGE_METRIC_TYPE = "usage" + """Usage data.""" + + +class OperationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the long running operation.""" + + RUNNING = "Running" + """RUNNING.""" + COMPLETED = "Completed" + """COMPLETED.""" + FAILED = "Failed" + """FAILED.""" class OperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """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. + """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.""" GREATER_THAN = "GreaterThan" - #: Alert will be triggered if the evaluated cost is greater than or equal to the threshold value. + """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_OR_EQUAL_TO = "GreaterThanOrEqualTo" + """Alert will be triggered if the evaluated cost is greater than or equal to the threshold value.""" + + +class OrganizationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The organization type of the lot.""" + + PRIMARY_ORGANIZATION_TYPE = "Primary" + """Primary organization type for Multi-Entity consumption commitment.""" + CONTRIBUTOR_ORGANIZATION_TYPE = "Contributor" + """Contributor organization type for Multi-Entity consumption commitment.""" class PricingModelType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Identifier that indicates how the meter is priced.""" ON_DEMAND = "On Demand" + """ON_DEMAND.""" RESERVATION = "Reservation" + """RESERVATION.""" SPOT = "Spot" + """SPOT.""" class ReservationRecommendationKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the kind of reservation recommendation.""" LEGACY = "legacy" + """LEGACY.""" MODERN = "modern" + """MODERN.""" class Scope(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Scope.""" + """Type of Scope.""" SINGLE = "Single" + """SINGLE.""" SHARED = "Shared" + """SHARED.""" class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The status of the lot.""" NONE = "None" + """NONE.""" ACTIVE = "Active" + """ACTIVE.""" INACTIVE = "Inactive" + """INACTIVE.""" EXPIRED = "Expired" + """EXPIRED.""" COMPLETE = "Complete" + """COMPLETE.""" CANCELED = "Canceled" + """CANCELED.""" class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Term.""" + """Type of Term.""" - #: 1 year reservation term + P1_M = "P1M" + """1 month reservation term.""" P1_Y = "P1Y" - #: 3 year reservation term + """1 year reservation term.""" P3_Y = "P3Y" + """3 year reservation term.""" class ThresholdType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """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. + """Actual costs budget alerts notify when the actual accrued cost exceeds the allocated budget .""" FORECASTED = "Forecasted" + """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.""" class TimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -188,15 +275,23 @@ class TimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """ MONTHLY = "Monthly" + """MONTHLY.""" QUARTERLY = "Quarterly" + """QUARTERLY.""" ANNUALLY = "Annually" + """ANNUALLY.""" BILLING_MONTH = "BillingMonth" + """BILLING_MONTH.""" BILLING_QUARTER = "BillingQuarter" + """BILLING_QUARTER.""" BILLING_ANNUAL = "BillingAnnual" + """BILLING_ANNUAL.""" class UsageDetailsKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the kind of usage details.""" LEGACY = "legacy" + """LEGACY.""" MODERN = "modern" + """MODERN.""" diff --git a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models.py b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models.py new file mode 100644 index 000000000000..38cb88451dff --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models.py @@ -0,0 +1,5396 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +import datetime +import decimal +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ._enums import ChargeSummaryKind, ReservationRecommendationKind, UsageDetailsKind + +if TYPE_CHECKING: + from .. import models as _models + + +class Amount(_Model): + """The amount plus currency . + + :ivar currency: Amount currency. + :vartype currency: str + :ivar value: Amount. + :vartype value: ~decimal.Decimal + """ + + currency: Optional[str] = rest_field(visibility=["read"]) + """Amount currency.""" + value: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """Amount.""" + + +class AmountWithExchangeRate(Amount): + """The amount with exchange rate. + + :ivar currency: Amount currency. + :vartype currency: str + :ivar value: Amount. + :vartype value: ~decimal.Decimal + :ivar exchange_rate: The exchange rate. + :vartype exchange_rate: ~decimal.Decimal + :ivar exchange_rate_month: The exchange rate month. + :vartype exchange_rate_month: int + """ + + exchange_rate: Optional[decimal.Decimal] = rest_field(name="exchangeRate", visibility=["read"]) + """The exchange rate.""" + exchange_rate_month: Optional[int] = rest_field(name="exchangeRateMonth", visibility=["read"]) + """The exchange rate month.""" + + +class Resource(_Model): + """Resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the resource.""" + type: Optional[str] = rest_field(visibility=["read"]) + """The type of the resource. E.g. \"Microsoft.Compute/virtualMachines\" or + \"Microsoft.Storage/storageAccounts\".""" + system_data: Optional["_models.SystemData"] = rest_field(name="systemData", visibility=["read"]) + """Azure Resource Manager metadata containing createdBy and modifiedBy information.""" + + +class Balance(Resource): + """A balance resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the balance. + :vartype properties: ~azure.mgmt.consumption.models.BalanceProperties + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + properties: Optional["_models.BalanceProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the balance.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = [ + "currency", + "beginning_balance", + "ending_balance", + "new_purchases", + "adjustments", + "utilized", + "service_overage", + "charges_billed_separately", + "total_overage", + "total_usage", + "azure_marketplace_service_charges", + "billing_frequency", + "price_hidden", + "overage_refund", + "new_purchases_details", + "adjustment_details", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.BalanceProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class BalanceProperties(_Model): + """The properties of the balance. + + :ivar currency: The ISO currency in which the meter is charged, for example, USD. + :vartype currency: str + :ivar beginning_balance: The beginning balance for the billing period. + :vartype beginning_balance: ~decimal.Decimal + :ivar ending_balance: The ending balance for the billing period (for open periods this will be + updated daily). + :vartype ending_balance: ~decimal.Decimal + :ivar new_purchases: Total new purchase amount. + :vartype new_purchases: ~decimal.Decimal + :ivar adjustments: Total adjustment amount. + :vartype adjustments: ~decimal.Decimal + :ivar utilized: Total Commitment usage. + :vartype utilized: ~decimal.Decimal + :ivar service_overage: Overage for Azure services. + :vartype service_overage: ~decimal.Decimal + :ivar charges_billed_separately: Charges Billed separately. + :vartype charges_billed_separately: ~decimal.Decimal + :ivar total_overage: serviceOverage + chargesBilledSeparately. + :vartype total_overage: ~decimal.Decimal + :ivar total_usage: Azure service commitment + total Overage. + :vartype total_usage: ~decimal.Decimal + :ivar azure_marketplace_service_charges: Total charges for Azure Marketplace. + :vartype azure_marketplace_service_charges: ~decimal.Decimal + :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 + :ivar overage_refund: Overage Refunds. + :vartype overage_refund: ~decimal.Decimal + :ivar new_purchases_details: List of new purchases. + :vartype new_purchases_details: + list[~azure.mgmt.consumption.models.BalancePropertiesNewPurchasesDetailsItem] + :ivar adjustment_details: List of Adjustments (Promo credit, SIE credit etc.). + :vartype adjustment_details: + list[~azure.mgmt.consumption.models.BalancePropertiesAdjustmentDetailsItem] + """ + + currency: Optional[str] = rest_field(visibility=["read"]) + """The ISO currency in which the meter is charged, for example, USD.""" + beginning_balance: Optional[decimal.Decimal] = rest_field(name="beginningBalance", visibility=["read"]) + """The beginning balance for the billing period.""" + ending_balance: Optional[decimal.Decimal] = rest_field(name="endingBalance", visibility=["read"]) + """The ending balance for the billing period (for open periods this will be updated daily).""" + new_purchases: Optional[decimal.Decimal] = rest_field(name="newPurchases", visibility=["read"]) + """Total new purchase amount.""" + adjustments: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """Total adjustment amount.""" + utilized: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """Total Commitment usage.""" + service_overage: Optional[decimal.Decimal] = rest_field(name="serviceOverage", visibility=["read"]) + """Overage for Azure services.""" + charges_billed_separately: Optional[decimal.Decimal] = rest_field( + name="chargesBilledSeparately", visibility=["read"] + ) + """Charges Billed separately.""" + total_overage: Optional[decimal.Decimal] = rest_field(name="totalOverage", visibility=["read"]) + """serviceOverage + chargesBilledSeparately.""" + total_usage: Optional[decimal.Decimal] = rest_field(name="totalUsage", visibility=["read"]) + """Azure service commitment + total Overage.""" + azure_marketplace_service_charges: Optional[decimal.Decimal] = rest_field( + name="azureMarketplaceServiceCharges", visibility=["read"] + ) + """Total charges for Azure Marketplace.""" + billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = rest_field( + name="billingFrequency", visibility=["read", "create", "update", "delete", "query"] + ) + """The billing frequency. Known values are: \"Month\", \"Quarter\", and \"Year\".""" + price_hidden: Optional[bool] = rest_field(name="priceHidden", visibility=["read"]) + """Price is hidden or not.""" + overage_refund: Optional[decimal.Decimal] = rest_field(name="overageRefund", visibility=["read"]) + """Overage Refunds.""" + new_purchases_details: Optional[list["_models.BalancePropertiesNewPurchasesDetailsItem"]] = rest_field( + name="newPurchasesDetails", visibility=["read"] + ) + """List of new purchases.""" + adjustment_details: Optional[list["_models.BalancePropertiesAdjustmentDetailsItem"]] = rest_field( + name="adjustmentDetails", visibility=["read"] + ) + """List of Adjustments (Promo credit, SIE credit etc.).""" + + @overload + def __init__( + self, + *, + billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BalancePropertiesAdjustmentDetailsItem(_Model): + """BalancePropertiesAdjustmentDetailsItem. + + :ivar name: the name of new adjustment. + :vartype name: str + :ivar value: the value of new adjustment. + :vartype value: ~decimal.Decimal + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """the name of new adjustment.""" + value: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """the value of new adjustment.""" + + +class BalancePropertiesNewPurchasesDetailsItem(_Model): + """BalancePropertiesNewPurchasesDetailsItem. + + :ivar name: the name of new purchase. + :vartype name: str + :ivar value: the value of new purchase. + :vartype value: ~decimal.Decimal + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """the name of new purchase.""" + value: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """the value of new purchase.""" + + +class ExtensionResource(Resource): + """The base extension resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + """ + + +class Budget(ExtensionResource): + """A budget resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the budget. + :vartype properties: ~azure.mgmt.consumption.models.BudgetProperties + :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 + """ + + properties: Optional["_models.BudgetProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the budget.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """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.""" + + __flattened_items = [ + "category", + "amount", + "time_grain", + "time_period", + "filter", + "current_spend", + "notifications", + "forecast_spend", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.BudgetProperties"] = None, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class BudgetComparisonExpression(_Model): + """The comparison expression to be used in the budgets. + + :ivar name: The name of the column to use in comparison. Required. + :vartype name: str + :ivar operator: The operator to use for comparison. Required. "In" + :vartype operator: str or ~azure.mgmt.consumption.models.BudgetOperatorType + :ivar values_property: Array of values to use for comparison. Required. + :vartype values_property: list[str] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the column to use in comparison. Required.""" + operator: Union[str, "_models.BudgetOperatorType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The operator to use for comparison. Required. \"In\"""" + values_property: list[str] = rest_field( + name="values", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="values" + ) + """Array of values to use for comparison. Required.""" + + @overload + def __init__( + self, + *, + name: str, + operator: Union[str, "_models.BudgetOperatorType"], + values_property: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BudgetFilter(_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: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression + """ + + and_property: Optional[list["_models.BudgetFilterProperties"]] = rest_field( + name="and", visibility=["read", "create", "update", "delete", "query"] + ) + """The logical \"AND\" expression. Must have at least 2 items.""" + dimensions: Optional["_models.BudgetComparisonExpression"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Has comparison expression for a dimension.""" + tags: Optional["_models.BudgetComparisonExpression"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Has comparison expression for a tag.""" + + @overload + def __init__( + self, + *, + and_property: Optional[list["_models.BudgetFilterProperties"]] = None, + dimensions: Optional["_models.BudgetComparisonExpression"] = None, + tags: Optional["_models.BudgetComparisonExpression"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BudgetFilterProperties(_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: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression + """ + + dimensions: Optional["_models.BudgetComparisonExpression"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Has comparison expression for a dimension.""" + tags: Optional["_models.BudgetComparisonExpression"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Has comparison expression for a tag.""" + + @overload + def __init__( + self, + *, + dimensions: Optional["_models.BudgetComparisonExpression"] = None, + tags: Optional["_models.BudgetComparisonExpression"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BudgetProperties(_Model): + """The properties of the budget. + + :ivar category: The category of the budget, whether the budget tracks cost or usage. Required. + "Cost" + :vartype category: str or ~azure.mgmt.consumption.models.CategoryType + :ivar amount: The total amount of cost to track with the budget. Required. + :vartype amount: ~decimal.Decimal + :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. Required. Known values are: "Monthly", "Quarterly", "Annually", "BillingMonth", + "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. + Future start date should not be more than twelve months. Past start date should be selected + within the timegrain period. There are no restrictions on the end date. Required. + :vartype time_period: ~azure.mgmt.consumption.models.BudgetTimePeriod + :ivar filter: May be used to filter budgets by user-specified dimensions and/or tags. + :vartype filter: ~azure.mgmt.consumption.models.BudgetFilter + :ivar current_spend: The current amount of cost which is being tracked for a budget. + :vartype current_spend: ~azure.mgmt.consumption.models.CurrentSpend + :ivar notifications: Dictionary of notifications associated with the budget. Budget can have up + to five notifications. + :vartype notifications: dict[str, ~azure.mgmt.consumption.models.Notification] + :ivar forecast_spend: The forecasted cost which is being tracked for a budget. + :vartype forecast_spend: ~azure.mgmt.consumption.models.ForecastSpend + """ + + category: Union[str, "_models.CategoryType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The category of the budget, whether the budget tracks cost or usage. Required. \"Cost\"""" + amount: decimal.Decimal = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The total amount of cost to track with the budget. Required.""" + time_grain: Union[str, "_models.TimeGrainType"] = rest_field( + name="timeGrain", visibility=["read", "create", "update", "delete", "query"] + ) + """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. Required. + Known values are: \"Monthly\", \"Quarterly\", \"Annually\", \"BillingMonth\", + \"BillingQuarter\", and \"BillingAnnual\".""" + time_period: "_models.BudgetTimePeriod" = rest_field( + name="timePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """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. Future start date + should not be more than twelve months. Past start date should be selected within the timegrain + period. There are no restrictions on the end date. Required.""" + filter: Optional["_models.BudgetFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """May be used to filter budgets by user-specified dimensions and/or tags.""" + current_spend: Optional["_models.CurrentSpend"] = rest_field(name="currentSpend", visibility=["read"]) + """The current amount of cost which is being tracked for a budget.""" + notifications: Optional[dict[str, "_models.Notification"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Dictionary of notifications associated with the budget. Budget can have up to five + notifications.""" + forecast_spend: Optional["_models.ForecastSpend"] = rest_field(name="forecastSpend", visibility=["read"]) + """The forecasted cost which is being tracked for a budget.""" + + @overload + def __init__( + self, + *, + category: Union[str, "_models.CategoryType"], + amount: decimal.Decimal, + time_grain: Union[str, "_models.TimeGrainType"], + time_period: "_models.BudgetTimePeriod", + filter: Optional["_models.BudgetFilter"] = None, # pylint: disable=redefined-builtin + notifications: Optional[dict[str, "_models.Notification"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BudgetTimePeriod(_Model): + """The start and end date for a 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. + :vartype end_date: ~datetime.datetime + """ + + start_date: datetime.datetime = rest_field( + name="startDate", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start date for the budget. Required.""" + end_date: Optional[datetime.datetime] = rest_field( + name="endDate", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end date for the budget. If not provided, we default this to 10 years from the start date.""" + + @overload + def __init__( + self, + *, + start_date: datetime.datetime, + end_date: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ChargesListResult(_Model): + """Result of listing charge summary. + + :ivar value: The list of charge summary. + :vartype value: list[~azure.mgmt.consumption.models.ChargeSummary] + """ + + value: Optional[list["_models.ChargeSummary"]] = rest_field(visibility=["read"]) + """The list of charge summary.""" + + +class ProxyResource(Resource): + """Proxy Resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + """ + + +class ChargeSummary(ProxyResource): + """A charge summary resource. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LegacyChargeSummary, ModernChargeSummary + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :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 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 + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Specifies the kind of charge summary. Required. Known values are: \"legacy\" and \"modern\".""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """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.""" + + @overload + def __init__( + self, + *, + kind: str, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreditBalanceSummary(_Model): + """Summary of credit balances. + + :ivar estimated_balance: Estimated balance. + :vartype estimated_balance: ~azure.mgmt.consumption.models.Amount + :ivar current_balance: Current balance. + :vartype current_balance: ~azure.mgmt.consumption.models.Amount + :ivar estimated_balance_in_billing_currency: Estimated balance in billing currency. + :vartype estimated_balance_in_billing_currency: + ~azure.mgmt.consumption.models.AmountWithExchangeRate + """ + + estimated_balance: Optional["_models.Amount"] = rest_field(name="estimatedBalance", visibility=["read"]) + """Estimated balance.""" + current_balance: Optional["_models.Amount"] = rest_field(name="currentBalance", visibility=["read"]) + """Current balance.""" + estimated_balance_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="estimatedBalanceInBillingCurrency", visibility=["read"] + ) + """Estimated balance in billing currency.""" + + +class CreditSummary(ProxyResource): + """A credit summary resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the credit summary. + :vartype properties: ~azure.mgmt.consumption.models.CreditSummaryProperties + :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 list of Tag. + :vartype tags: dict[str, str] + """ + + properties: Optional["_models.CreditSummaryProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the credit summary.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """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.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of Tag.""" + + __flattened_items = [ + "balance_summary", + "pending_credit_adjustments", + "expired_credit", + "pending_eligible_charges", + "credit_currency", + "billing_currency", + "reseller", + "is_estimated_balance", + "e_tag", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.CreditSummaryProperties"] = None, + e_tag: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class CreditSummaryProperties(_Model): + """The properties of the credit summary. + + :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. + :vartype pending_credit_adjustments: ~azure.mgmt.consumption.models.Amount + :ivar expired_credit: Expired credit. + :vartype expired_credit: ~azure.mgmt.consumption.models.Amount + :ivar pending_eligible_charges: Pending eligible charges. + :vartype pending_eligible_charges: ~azure.mgmt.consumption.models.Amount + :ivar credit_currency: The credit currency. + :vartype credit_currency: str + :ivar billing_currency: The billing currency. + :vartype billing_currency: str + :ivar reseller: Credit's reseller. + :vartype reseller: ~azure.mgmt.consumption.models.Reseller + :ivar is_estimated_balance: If true, the listed details are based on an estimation and it will + be subjected to change. + :vartype is_estimated_balance: bool + :ivar e_tag: The eTag for the resource. + :vartype e_tag: str + """ + + balance_summary: Optional["_models.CreditBalanceSummary"] = rest_field(name="balanceSummary", visibility=["read"]) + """Summary of balances associated with this credit summary.""" + pending_credit_adjustments: Optional["_models.Amount"] = rest_field( + name="pendingCreditAdjustments", visibility=["read"] + ) + """Pending credit adjustments.""" + expired_credit: Optional["_models.Amount"] = rest_field(name="expiredCredit", visibility=["read"]) + """Expired credit.""" + pending_eligible_charges: Optional["_models.Amount"] = rest_field( + name="pendingEligibleCharges", visibility=["read"] + ) + """Pending eligible charges.""" + credit_currency: Optional[str] = rest_field(name="creditCurrency", visibility=["read"]) + """The credit currency.""" + billing_currency: Optional[str] = rest_field(name="billingCurrency", visibility=["read"]) + """The billing currency.""" + reseller: Optional["_models.Reseller"] = rest_field(visibility=["read"]) + """Credit's reseller.""" + is_estimated_balance: Optional[bool] = rest_field(name="isEstimatedBalance", visibility=["read"]) + """If true, the listed details are based on an estimation and it will be subjected to change.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read"]) + """The eTag for the resource.""" + + +class CurrentSpend(_Model): + """The current amount of cost which is being tracked for a budget. + + :ivar amount: The total amount of cost which is being tracked by the budget. + :vartype amount: ~decimal.Decimal + :ivar unit: The unit of measure for the budget amount. + :vartype unit: str + """ + + amount: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The total amount of cost which is being tracked by the budget.""" + unit: Optional[str] = rest_field(visibility=["read"]) + """The unit of measure for the budget amount.""" + + +class ErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + type: Optional[str] = rest_field(visibility=["read"]) + """The additional info type.""" + info: Optional[Any] = rest_field(visibility=["read"]) + """The additional info.""" + + +class ErrorDetail(_Model): + """The error detail. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.consumption.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.consumption.models.ErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read"]) + """The error target.""" + details: Optional[list["_models.ErrorDetail"]] = rest_field(visibility=["read"]) + """The error details.""" + additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read"] + ) + """The error additional info.""" + + +class ErrorResponse(_Model): + """Error response. + + :ivar error: The error object. + :vartype error: ~azure.mgmt.consumption.models.ErrorDetail + """ + + error: Optional["_models.ErrorDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error object.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EventProperties(_Model): + """The event properties. + + :ivar transaction_date: The date of the event. + :vartype transaction_date: ~datetime.datetime + :ivar description: The description of the event. + :vartype description: str + :ivar new_credit: The amount of new credit or commitment for NewCredit or SettleCharges event. + :vartype new_credit: ~azure.mgmt.consumption.models.Amount + :ivar adjustments: The amount of balance adjustment. The property is not available for + ConsumptionCommitment lots. + :vartype adjustments: ~azure.mgmt.consumption.models.Amount + :ivar credit_expired: The amount of expired credit or commitment for NewCredit or SettleCharges + event. + :vartype credit_expired: ~azure.mgmt.consumption.models.Amount + :ivar charges: The amount of charges for events of type SettleCharges and + PendingEligibleCharges. + :vartype charges: ~azure.mgmt.consumption.models.Amount + :ivar closed_balance: The balance after the event, Note: This will not be returned for + Contributor Organization Type in Multi-Entity consumption commitment. + :vartype closed_balance: ~azure.mgmt.consumption.models.Amount + :ivar billing_account_id: Identifier of the billing account. + :vartype billing_account_id: str + :ivar billing_account_display_name: Name of the billing account. + :vartype billing_account_display_name: str + :ivar event_type: Identifies the type of the event. Known values are: "SettledCharges", + "PendingCharges", "PendingAdjustments", "PendingNewCredit", "PendingExpiredCredit", "UnKnown", + "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. + :vartype invoice_number: str + :ivar billing_profile_id: The ID that uniquely identifies the billing profile for which the + event happened. The property is only available for billing account of type + MicrosoftCustomerAgreement. + :vartype billing_profile_id: str + :ivar billing_profile_display_name: The display name of the billing profile for which the event + happened. The property is only available for billing account of type + MicrosoftCustomerAgreement. + :vartype billing_profile_display_name: str + :ivar lot_id: The ID that uniquely identifies the lot for which the event happened. + :vartype lot_id: str + :ivar lot_source: Identifies the source of the lot for which the event happened. + :vartype lot_source: str + :ivar canceled_credit: Amount of canceled credit. + :vartype canceled_credit: ~azure.mgmt.consumption.models.Amount + :ivar credit_currency: The credit currency of the event. + :vartype credit_currency: str + :ivar billing_currency: The billing currency of the event. + :vartype billing_currency: str + :ivar reseller: The reseller of the event. + :vartype reseller: ~azure.mgmt.consumption.models.Reseller + :ivar credit_expired_in_billing_currency: The amount of expired credit or commitment for + NewCredit or SettleCharges event in billing currency. + :vartype credit_expired_in_billing_currency: + ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar new_credit_in_billing_currency: The amount of new credit or commitment for NewCredit or + SettleCharges event in billing currency. + :vartype new_credit_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar adjustments_in_billing_currency: The amount of balance adjustment in billing currency. + :vartype adjustments_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar charges_in_billing_currency: The amount of charges for events of type SettleCharges and + PendingEligibleCharges in billing currency. + :vartype charges_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar closed_balance_in_billing_currency: The balance in billing currency after the event, + Note: This will not be returned for Contributor Organization Type in Multi-Entity consumption + commitment. + :vartype closed_balance_in_billing_currency: + ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar is_estimated_balance: If true, the listed details are based on an estimation and it will + be subjected to change. + :vartype is_estimated_balance: bool + :ivar e_tag: The eTag for the resource. + :vartype e_tag: str + """ + + transaction_date: Optional[datetime.datetime] = rest_field( + name="transactionDate", visibility=["read"], format="rfc3339" + ) + """The date of the event.""" + description: Optional[str] = rest_field(visibility=["read"]) + """The description of the event.""" + new_credit: Optional["_models.Amount"] = rest_field(name="newCredit", visibility=["read"]) + """The amount of new credit or commitment for NewCredit or SettleCharges event.""" + adjustments: Optional["_models.Amount"] = rest_field(visibility=["read"]) + """The amount of balance adjustment. The property is not available for ConsumptionCommitment lots.""" + credit_expired: Optional["_models.Amount"] = rest_field(name="creditExpired", visibility=["read"]) + """The amount of expired credit or commitment for NewCredit or SettleCharges event.""" + charges: Optional["_models.Amount"] = rest_field(visibility=["read"]) + """The amount of charges for events of type SettleCharges and PendingEligibleCharges.""" + closed_balance: Optional["_models.Amount"] = rest_field(name="closedBalance", visibility=["read"]) + """The balance after the event, Note: This will not be returned for Contributor Organization Type + in Multi-Entity consumption commitment.""" + billing_account_id: Optional[str] = rest_field(name="billingAccountId", visibility=["read"]) + """Identifier of the billing account.""" + billing_account_display_name: Optional[str] = rest_field(name="billingAccountDisplayName", visibility=["read"]) + """Name of the billing account.""" + event_type: Optional[Union[str, "_models.EventType"]] = rest_field( + name="eventType", visibility=["read", "create", "update", "delete", "query"] + ) + """Identifies the type of the event. Known values are: \"SettledCharges\", \"PendingCharges\", + \"PendingAdjustments\", \"PendingNewCredit\", \"PendingExpiredCredit\", \"UnKnown\", + \"NewCredit\", and \"CreditExpired\".""" + invoice_number: Optional[str] = rest_field(name="invoiceNumber", visibility=["read"]) + """The number which uniquely identifies the invoice on which the event was billed. This will be + empty for unbilled events.""" + billing_profile_id: Optional[str] = rest_field(name="billingProfileId", visibility=["read"]) + """The ID that uniquely identifies the billing profile for which the event happened. The property + is only available for billing account of type MicrosoftCustomerAgreement.""" + billing_profile_display_name: Optional[str] = rest_field(name="billingProfileDisplayName", visibility=["read"]) + """The display name of the billing profile for which the event happened. The property is only + available for billing account of type MicrosoftCustomerAgreement.""" + lot_id: Optional[str] = rest_field(name="lotId", visibility=["read"]) + """The ID that uniquely identifies the lot for which the event happened.""" + lot_source: Optional[str] = rest_field(name="lotSource", visibility=["read"]) + """Identifies the source of the lot for which the event happened.""" + canceled_credit: Optional["_models.Amount"] = rest_field(name="canceledCredit", visibility=["read"]) + """Amount of canceled credit.""" + credit_currency: Optional[str] = rest_field(name="creditCurrency", visibility=["read"]) + """The credit currency of the event.""" + billing_currency: Optional[str] = rest_field(name="billingCurrency", visibility=["read"]) + """The billing currency of the event.""" + reseller: Optional["_models.Reseller"] = rest_field(visibility=["read"]) + """The reseller of the event.""" + credit_expired_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="creditExpiredInBillingCurrency", visibility=["read"] + ) + """The amount of expired credit or commitment for NewCredit or SettleCharges event in billing + currency.""" + new_credit_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="newCreditInBillingCurrency", visibility=["read"] + ) + """The amount of new credit or commitment for NewCredit or SettleCharges event in billing + currency.""" + adjustments_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="adjustmentsInBillingCurrency", visibility=["read"] + ) + """The amount of balance adjustment in billing currency.""" + charges_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="chargesInBillingCurrency", visibility=["read"] + ) + """The amount of charges for events of type SettleCharges and PendingEligibleCharges in billing + currency.""" + closed_balance_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="closedBalanceInBillingCurrency", visibility=["read"] + ) + """The balance in billing currency after the event, Note: This will not be returned for + Contributor Organization Type in Multi-Entity consumption commitment.""" + is_estimated_balance: Optional[bool] = rest_field(name="isEstimatedBalance", visibility=["read"]) + """If true, the listed details are based on an estimation and it will be subjected to change.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read"]) + """The eTag for the resource.""" + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + event_type: Optional[Union[str, "_models.EventType"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EventSummary(ProxyResource): + """An event summary resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The event properties. + :vartype properties: ~azure.mgmt.consumption.models.EventProperties + :ivar e_tag: The eTag for the resource. + :vartype e_tag: str + """ + + properties: Optional["_models.EventProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The event properties.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read"]) + """The eTag for the resource.""" + + __flattened_items = [ + "transaction_date", + "description", + "new_credit", + "adjustments", + "credit_expired", + "charges", + "closed_balance", + "billing_account_id", + "billing_account_display_name", + "event_type", + "invoice_number", + "billing_profile_id", + "billing_profile_display_name", + "lot_id", + "lot_source", + "canceled_credit", + "credit_currency", + "billing_currency", + "reseller", + "credit_expired_in_billing_currency", + "new_credit_in_billing_currency", + "adjustments_in_billing_currency", + "charges_in_billing_currency", + "closed_balance_in_billing_currency", + "is_estimated_balance", + "e_tag", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.EventProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ForecastSpend(_Model): + """The forecasted cost which is being tracked for a budget. + + :ivar amount: The forecasted cost for the total time period which is being tracked by the + budget. This value is only provided if the budget contains a forecast alert type. + :vartype amount: ~decimal.Decimal + :ivar unit: The unit of measure for the budget amount. + :vartype unit: str + """ + + amount: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The forecasted cost for the total time period which is being tracked by the budget. This value + is only provided if the budget contains a forecast alert type.""" + unit: Optional[str] = rest_field(visibility=["read"]) + """The unit of measure for the budget amount.""" + + +class HighCasedErrorDetails(_Model): + """The details of the error. + + :ivar code: Error code. + :vartype code: str + :ivar message: Error message indicating why the operation failed. + :vartype message: str + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """Error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """Error message indicating why the operation failed.""" + + +class HighCasedErrorResponse(_Model): + """Error response indicates that the service is not able to process the incoming request. The + reason is provided in the error message. + + Some Error responses: + + + + * 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the + "x-ms-ratelimit-microsoft.consumption-retry-after" header. + + * 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time + specified in the "Retry-After" header. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails + """ + + error: Optional["_models.HighCasedErrorDetails"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The details of the error.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.HighCasedErrorDetails"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LegacyChargeSummary(ChargeSummary, discriminator="legacy"): + """Legacy charge summary. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :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 properties: Properties for legacy charge summary. Required. + :vartype properties: ~azure.mgmt.consumption.models.LegacyChargeSummaryProperties + :ivar kind: Specifies the kind of charge summary. Required. LEGACY. + :vartype kind: str or ~azure.mgmt.consumption.models.LEGACY + """ + + properties: "_models.LegacyChargeSummaryProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for legacy charge summary. Required.""" + kind: Literal[ChargeSummaryKind.LEGACY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Specifies the kind of charge summary. Required. LEGACY.""" + + __flattened_items = [ + "billing_period_id", + "usage_start", + "usage_end", + "azure_charges", + "charges_billed_separately", + "azure_marketplace_charges", + "currency", + ] + + @overload + def __init__( + self, + *, + properties: "_models.LegacyChargeSummaryProperties", + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class LegacyChargeSummaryProperties(_Model): + """The properties of legacy charge summary. + + :ivar billing_period_id: The id of the billing period resource that the charge belongs to. + :vartype billing_period_id: str + :ivar usage_start: Usage start date. + :vartype usage_start: str + :ivar usage_end: Usage end date. + :vartype usage_end: str + :ivar azure_charges: Azure Charges. + :vartype azure_charges: ~decimal.Decimal + :ivar charges_billed_separately: Charges Billed separately. + :vartype charges_billed_separately: ~decimal.Decimal + :ivar azure_marketplace_charges: Marketplace Charges. + :vartype azure_marketplace_charges: ~decimal.Decimal + :ivar currency: Currency Code. + :vartype currency: str + """ + + billing_period_id: Optional[str] = rest_field(name="billingPeriodId", visibility=["read"]) + """The id of the billing period resource that the charge belongs to.""" + usage_start: Optional[str] = rest_field(name="usageStart", visibility=["read"]) + """Usage start date.""" + usage_end: Optional[str] = rest_field(name="usageEnd", visibility=["read"]) + """Usage end date.""" + azure_charges: Optional[decimal.Decimal] = rest_field(name="azureCharges", visibility=["read"]) + """Azure Charges.""" + charges_billed_separately: Optional[decimal.Decimal] = rest_field( + name="chargesBilledSeparately", visibility=["read"] + ) + """Charges Billed separately.""" + azure_marketplace_charges: Optional[decimal.Decimal] = rest_field( + name="azureMarketplaceCharges", visibility=["read"] + ) + """Marketplace Charges.""" + currency: Optional[str] = rest_field(visibility=["read"]) + """Currency Code.""" + + +class ReservationRecommendation(_Model): + """A reservation recommendation resource. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LegacyReservationRecommendation, ModernReservationRecommendation + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar location: Resource location. + :vartype location: str + :ivar sku: Resource sku. + :vartype sku: str + :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 reservation recommendation. Required. Known values are: + "legacy" and "modern". + :vartype kind: str or ~azure.mgmt.consumption.models.ReservationRecommendationKind + """ + + __mapping__: dict[str, _Model] = {} + id: Optional[str] = rest_field(visibility=["read"]) + """Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the resource.""" + type: Optional[str] = rest_field(visibility=["read"]) + """The type of the resource. E.g. \"Microsoft.Compute/virtualMachines\" or + \"Microsoft.Storage/storageAccounts\".""" + system_data: Optional["_models.SystemData"] = rest_field(name="systemData", visibility=["read"]) + """Azure Resource Manager metadata containing createdBy and modifiedBy information.""" + location: Optional[str] = rest_field(visibility=["read"]) + """Resource location.""" + sku: Optional[str] = rest_field(visibility=["read"]) + """Resource sku.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Specifies the kind of reservation recommendation. Required. Known values are: \"legacy\" and + \"modern\".""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LegacyReservationRecommendation(ReservationRecommendation, discriminator="legacy"): + """Legacy reservation recommendation. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar location: Resource location. + :vartype location: str + :ivar sku: Resource sku. + :vartype sku: str + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties for legacy reservation recommendation. Required. + :vartype properties: ~azure.mgmt.consumption.models.LegacyReservationRecommendationProperties + :ivar kind: Specifies the kind of reservation recommendation. Required. LEGACY. + :vartype kind: str or ~azure.mgmt.consumption.models.LEGACY + """ + + properties: "_models.LegacyReservationRecommendationProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for legacy reservation recommendation. Required.""" + kind: Literal[ReservationRecommendationKind.LEGACY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Specifies the kind of reservation recommendation. Required. LEGACY.""" + + @overload + def __init__( + self, + *, + properties: "_models.LegacyReservationRecommendationProperties", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = ReservationRecommendationKind.LEGACY # type: ignore + + +class LegacyReservationRecommendationProperties(_Model): # pylint: disable=name-too-long + """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 + + :ivar look_back_period: The number of days of usage to look back for recommendation. + :vartype look_back_period: str + :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 resource_type: The azure resource type. + :vartype resource_type: str + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. + :vartype term: str + :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. + :vartype cost_with_no_reserved_instances: ~decimal.Decimal + :ivar recommended_quantity: Recommended quality for reserved instances. + :vartype recommended_quantity: ~decimal.Decimal + :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. + :vartype total_cost_with_reserved_instances: ~decimal.Decimal + :ivar net_savings: Total estimated savings with reserved instances. + :vartype net_savings: ~decimal.Decimal + :ivar first_usage_date: The usage date for looking back. + :vartype first_usage_date: ~datetime.datetime + :ivar scope: Shared or single recommendation. Required. Default value is None. + :vartype scope: str + :ivar sku_properties: List of sku properties. + :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int + """ + + __mapping__: dict[str, _Model] = {} + look_back_period: Optional[str] = rest_field(name="lookBackPeriod", visibility=["read"]) + """The number of days of usage to look back for recommendation.""" + instance_flexibility_ratio: Optional[float] = rest_field(name="instanceFlexibilityRatio", visibility=["read"]) + """The instance Flexibility Ratio.""" + instance_flexibility_group: Optional[str] = rest_field(name="instanceFlexibilityGroup", visibility=["read"]) + """The instance Flexibility Group.""" + normalized_size: Optional[str] = rest_field(name="normalizedSize", visibility=["read"]) + """The normalized Size.""" + recommended_quantity_normalized: Optional[float] = rest_field( + name="recommendedQuantityNormalized", visibility=["read"] + ) + """The recommended Quantity Normalized.""" + meter_id: Optional[str] = rest_field(name="meterId", visibility=["read"]) + """The meter id (GUID).""" + resource_type: Optional[str] = rest_field(name="resourceType", visibility=["read"]) + """The azure resource type.""" + term: Optional[str] = rest_field(visibility=["read"]) + """Term period of the reservation. ex: P1M, P1Y or P3Y.""" + cost_with_no_reserved_instances: Optional[decimal.Decimal] = rest_field( + name="costWithNoReservedInstances", visibility=["read"] + ) + """The total amount of cost without reserved instances.""" + recommended_quantity: Optional[decimal.Decimal] = rest_field(name="recommendedQuantity", visibility=["read"]) + """Recommended quality for reserved instances.""" + total_cost_with_reserved_instances: Optional[decimal.Decimal] = rest_field( + name="totalCostWithReservedInstances", visibility=["read"] + ) + """The total amount of cost with reserved instances.""" + net_savings: Optional[decimal.Decimal] = rest_field(name="netSavings", visibility=["read"]) + """Total estimated savings with reserved instances.""" + first_usage_date: Optional[datetime.datetime] = rest_field( + name="firstUsageDate", visibility=["read"], format="rfc3339" + ) + """The usage date for looking back.""" + scope: str = rest_discriminator(name="scope", visibility=["read", "create", "update", "delete", "query"]) + """Shared or single recommendation. Required. Default value is None.""" + sku_properties: Optional[list["_models.SkuProperty"]] = rest_field(name="skuProperties", visibility=["read"]) + """List of sku properties.""" + last_usage_date: Optional[datetime.datetime] = rest_field( + name="lastUsageDate", visibility=["read"], format="rfc3339" + ) + """The last usage date used for looking back for computing the recommendation.""" + total_hours: Optional[int] = rest_field(name="totalHours", visibility=["read"]) + """The total hours for which the cost is covered.""" + + @overload + def __init__( + self, + *, + scope: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LegacyReservationTransactionProperties(_Model): + """The properties of a legacy reservation transaction. + + :ivar event_date: The date of the transaction. + :vartype event_date: ~datetime.datetime + :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 + order contains reservations. The reservation order specifies the VM size and region for the + reservations. + :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 or Refund). + :vartype event_type: str + :ivar quantity: The quantity of the transaction. + :vartype quantity: ~decimal.Decimal + :ivar amount: The charge of the transaction. + :vartype amount: ~decimal.Decimal + :ivar currency: The ISO currency in which the transaction is charged, for example, USD. + :vartype currency: str + :ivar reservation_order_name: The name of the reservation order. + :vartype reservation_order_name: str + :ivar purchasing_enrollment: The purchasing enrollment. + :vartype purchasing_enrollment: str + :ivar purchasing_subscription_guid: The subscription guid that makes the transaction. + :vartype purchasing_subscription_guid: str + :ivar purchasing_subscription_name: The subscription name that makes the transaction. + :vartype purchasing_subscription_name: str + :ivar arm_sku_name: This is the ARM Sku name. It can be used to join with the serviceType field + in additional info in usage records. + :vartype arm_sku_name: str + :ivar term: This is the term of the transaction. + :vartype term: str + :ivar region: The region of the transaction. + :vartype region: str + :ivar account_name: The name of the account that makes the transaction. + :vartype account_name: str + :ivar account_owner_email: The email of the account owner that makes the transaction. + :vartype account_owner_email: str + :ivar department_name: The department name. + :vartype department_name: str + :ivar cost_center: The cost center of this department if it is a department and a cost center + is provided. + :vartype cost_center: str + :ivar current_enrollment: The current enrollment. + :vartype current_enrollment: str + :ivar billing_frequency: The billing frequency, which can be either one-time or recurring. + :vartype billing_frequency: str + :ivar billing_month: The billing month(yyyyMMdd), on which the event initiated. + :vartype billing_month: int + :ivar monetary_commitment: The monetary commitment amount at the enrollment scope. + :vartype monetary_commitment: ~decimal.Decimal + :ivar overage: The overage amount at the enrollment scope. + :vartype overage: ~decimal.Decimal + """ + + event_date: Optional[datetime.datetime] = rest_field(name="eventDate", visibility=["read"], format="rfc3339") + """The date of the transaction.""" + reservation_order_id: Optional[str] = rest_field(name="reservationOrderId", visibility=["read"]) + """The reservation order ID is the identifier for a reservation purchase. Each reservation order + ID represents a single purchase transaction. A reservation order contains reservations. The + reservation order specifies the VM size and region for the reservations.""" + description: Optional[str] = rest_field(visibility=["read"]) + """The description of the transaction.""" + event_type: Optional[str] = rest_field(name="eventType", visibility=["read"]) + """The type of the transaction (Purchase, Cancel or Refund).""" + quantity: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The quantity of the transaction.""" + amount: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The charge of the transaction.""" + currency: Optional[str] = rest_field(visibility=["read"]) + """The ISO currency in which the transaction is charged, for example, USD.""" + reservation_order_name: Optional[str] = rest_field(name="reservationOrderName", visibility=["read"]) + """The name of the reservation order.""" + purchasing_enrollment: Optional[str] = rest_field(name="purchasingEnrollment", visibility=["read"]) + """The purchasing enrollment.""" + purchasing_subscription_guid: Optional[str] = rest_field(name="purchasingSubscriptionGuid", visibility=["read"]) + """The subscription guid that makes the transaction.""" + purchasing_subscription_name: Optional[str] = rest_field(name="purchasingSubscriptionName", visibility=["read"]) + """The subscription name that makes the transaction.""" + arm_sku_name: Optional[str] = rest_field(name="armSkuName", visibility=["read"]) + """This is the ARM Sku name. It can be used to join with the serviceType field in additional info + in usage records.""" + term: Optional[str] = rest_field(visibility=["read"]) + """This is the term of the transaction.""" + region: Optional[str] = rest_field(visibility=["read"]) + """The region of the transaction.""" + account_name: Optional[str] = rest_field(name="accountName", visibility=["read"]) + """The name of the account that makes the transaction.""" + account_owner_email: Optional[str] = rest_field(name="accountOwnerEmail", visibility=["read"]) + """The email of the account owner that makes the transaction.""" + department_name: Optional[str] = rest_field(name="departmentName", visibility=["read"]) + """The department name.""" + cost_center: Optional[str] = rest_field(name="costCenter", visibility=["read"]) + """The cost center of this department if it is a department and a cost center is provided.""" + current_enrollment: Optional[str] = rest_field(name="currentEnrollment", visibility=["read"]) + """The current enrollment.""" + billing_frequency: Optional[str] = rest_field(name="billingFrequency", visibility=["read"]) + """The billing frequency, which can be either one-time or recurring.""" + billing_month: Optional[int] = rest_field(name="billingMonth", visibility=["read"]) + """The billing month(yyyyMMdd), on which the event initiated.""" + monetary_commitment: Optional[decimal.Decimal] = rest_field(name="monetaryCommitment", visibility=["read"]) + """The monetary commitment amount at the enrollment scope.""" + overage: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The overage amount at the enrollment scope.""" + + +class LegacySharedScopeReservationRecommendationProperties( + LegacyReservationRecommendationProperties, discriminator="Shared" +): # pylint: disable=name-too-long + """The properties of the legacy reservation recommendation for shared scope. + + :ivar look_back_period: The number of days of usage to look back for recommendation. + :vartype look_back_period: str + :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 resource_type: The azure resource type. + :vartype resource_type: str + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. + :vartype term: str + :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. + :vartype cost_with_no_reserved_instances: ~decimal.Decimal + :ivar recommended_quantity: Recommended quality for reserved instances. + :vartype recommended_quantity: ~decimal.Decimal + :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. + :vartype total_cost_with_reserved_instances: ~decimal.Decimal + :ivar net_savings: Total estimated savings with reserved instances. + :vartype net_savings: ~decimal.Decimal + :ivar first_usage_date: The usage date for looking back. + :vartype first_usage_date: ~datetime.datetime + :ivar sku_properties: List of sku properties. + :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int + :ivar scope: Shared or single recommendation. Required. Default value is "Shared". + :vartype scope: str + """ + + scope: Literal["Shared"] = rest_discriminator(name="scope", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Shared or single recommendation. Required. Default value is \"Shared\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.scope = "Shared" # type: ignore + + +class LegacySingleScopeReservationRecommendationProperties( + LegacyReservationRecommendationProperties, discriminator="Single" +): # pylint: disable=name-too-long + """The properties of the legacy reservation recommendation for single scope. + + :ivar look_back_period: The number of days of usage to look back for recommendation. + :vartype look_back_period: str + :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 resource_type: The azure resource type. + :vartype resource_type: str + :ivar term: Term period of the reservation. ex: P1M, P1Y or P3Y. + :vartype term: str + :ivar cost_with_no_reserved_instances: The total amount of cost without reserved instances. + :vartype cost_with_no_reserved_instances: ~decimal.Decimal + :ivar recommended_quantity: Recommended quality for reserved instances. + :vartype recommended_quantity: ~decimal.Decimal + :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. + :vartype total_cost_with_reserved_instances: ~decimal.Decimal + :ivar net_savings: Total estimated savings with reserved instances. + :vartype net_savings: ~decimal.Decimal + :ivar first_usage_date: The usage date for looking back. + :vartype first_usage_date: ~datetime.datetime + :ivar sku_properties: List of sku properties. + :vartype sku_properties: list[~azure.mgmt.consumption.models.SkuProperty] + :ivar last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int + :ivar subscription_id: Subscription id associated with single scoped recommendation. + :vartype subscription_id: str + :ivar scope: Shared or single recommendation. Required. Default value is "Single". + :vartype scope: str + """ + + subscription_id: Optional[str] = rest_field(name="subscriptionId", visibility=["read"]) + """Subscription id associated with single scoped recommendation.""" + scope: Literal["Single"] = rest_discriminator(name="scope", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Shared or single recommendation. Required. Default value is \"Single\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.scope = "Single" # type: ignore + + +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 + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :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 etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Specifies the kind of usage details. Required. Known values are: \"legacy\" and \"modern\".""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class LegacyUsageDetail(UsageDetail, discriminator="legacy"): + """Legacy usage detail. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties for legacy usage details. Required. + :vartype properties: ~azure.mgmt.consumption.models.LegacyUsageDetailProperties + :ivar kind: Specifies the kind of usage details. Required. LEGACY. + :vartype kind: str or ~azure.mgmt.consumption.models.LEGACY + """ + + properties: "_models.LegacyUsageDetailProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for legacy usage details. Required.""" + kind: Literal[UsageDetailsKind.LEGACY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Specifies the kind of usage details. Required. LEGACY.""" + + __flattened_items = [ + "billing_account_id", + "billing_account_name", + "billing_period_start_date", + "billing_period_end_date", + "billing_profile_id", + "billing_profile_name", + "account_owner_id", + "account_name", + "subscription_id", + "subscription_name", + "date", + "product", + "part_number", + "meter_id", + "meter_details", + "quantity", + "effective_price", + "cost", + "unit_price", + "billing_currency", + "resource_location", + "consumed_service", + "resource_id", + "resource_name", + "service_info1", + "service_info2", + "additional_info", + "invoice_section", + "cost_center", + "resource_group", + "reservation_id", + "reservation_name", + "product_order_id", + "product_order_name", + "offer_id", + "is_azure_credit_eligible", + "term", + "publisher_name", + "publisher_type", + "plan_name", + "charge_type", + "frequency", + "pay_g_price", + "benefit_id", + "benefit_name", + "pricing_model", + ] + + @overload + def __init__( + self, + *, + properties: "_models.LegacyUsageDetailProperties", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class LegacyUsageDetailProperties(_Model): + """The properties of the legacy usage detail. + + :ivar billing_account_id: Billing Account identifier. + :vartype billing_account_id: str + :ivar billing_account_name: Billing Account Name. + :vartype billing_account_name: str + :ivar billing_period_start_date: The billing period start date. + :vartype billing_period_start_date: ~datetime.datetime + :ivar billing_period_end_date: The billing period end date. + :vartype billing_period_end_date: ~datetime.datetime + :ivar billing_profile_id: Billing Profile identifier. + :vartype billing_profile_id: str + :ivar billing_profile_name: Billing Profile Name. + :vartype billing_profile_name: str + :ivar account_owner_id: Account Owner Id. + :vartype account_owner_id: str + :ivar account_name: Account Name. + :vartype account_name: str + :ivar subscription_id: Subscription guid. + :vartype subscription_id: str + :ivar subscription_name: Subscription name. + :vartype subscription_name: str + :ivar date: Date for the usage record. + :vartype date: ~datetime.datetime + :ivar product: Product name for the consumed service or purchase. Not available for + Marketplace. + :vartype product: str + :ivar part_number: Part Number of the service used. Can be used to join with the price sheet. + Not available for marketplace. + :vartype part_number: str + :ivar meter_id: The meter id (GUID). Not available for marketplace. For reserved instance this + represents the primary meter for which the reservation was purchased. For the actual VM Size + for which the reservation is purchased see productOrderName. + :vartype meter_id: str + :ivar meter_details: The details about the meter. By default this is not populated, unless it's + specified in $expand. + :vartype meter_details: ~azure.mgmt.consumption.models.MeterDetailsResponse + :ivar quantity: The usage quantity. + :vartype quantity: ~decimal.Decimal + :ivar effective_price: Effective Price that's charged for the usage. + :vartype effective_price: ~decimal.Decimal + :ivar cost: The amount of cost before tax. + :vartype cost: ~decimal.Decimal + :ivar unit_price: Unit Price is the price applicable to you. (your EA or other contract price). + :vartype unit_price: ~decimal.Decimal + :ivar billing_currency: Billing Currency. + :vartype billing_currency: str + :ivar resource_location: Resource Location. + :vartype resource_location: str + :ivar consumed_service: Consumed service name. Name of the azure resource provider that emits + the usage or was purchased. This value is not provided for marketplace usage. + :vartype consumed_service: str + :ivar resource_id: Unique identifier of the Azure Resource Manager usage detail resource. + :vartype resource_id: str + :ivar resource_name: Resource Name. + :vartype resource_name: str + :ivar service_info1: Service-specific metadata. + :vartype service_info1: str + :ivar service_info2: Legacy field with optional service-specific metadata. + :vartype service_info2: str + :ivar additional_info: Additional details of this usage item. By default this is not populated, + unless it's specified in $expand. Use this field to get usage line item specific details such + as the actual VM Size (ServiceType) or the ratio in which the reservation discount is applied. + :vartype additional_info: str + :ivar invoice_section: Invoice Section Name. + :vartype invoice_section: str + :ivar cost_center: The cost center of this department if it is a department and a cost center + is provided. + :vartype cost_center: str + :ivar resource_group: Resource Group Name. + :vartype resource_group: str + :ivar reservation_id: ARM resource id of the reservation. Only applies to records relevant to + reservations. + :vartype reservation_id: str + :ivar reservation_name: User provided display name of the reservation. Last known name for a + particular day is populated in the daily data. Only applies to records relevant to + reservations. + :vartype reservation_name: str + :ivar product_order_id: Product Order Id. For reservations this is the Reservation Order ID. + :vartype product_order_id: str + :ivar product_order_name: Product Order Name. For reservations this is the SKU that was + purchased. + :vartype product_order_name: str + :ivar offer_id: Offer Id. Ex: MS-AZR-0017P, MS-AZR-0148P. + :vartype offer_id: str + :ivar is_azure_credit_eligible: Is Azure Credit Eligible. + :vartype is_azure_credit_eligible: bool + :ivar term: Term (in months). 1 month for monthly recurring purchase. 12 months for a 1 year + reservation. 36 months for a 3 year reservation. + :vartype term: str + :ivar publisher_name: Publisher Name. + :vartype publisher_name: str + :ivar publisher_type: Publisher Type. + :vartype publisher_type: str + :ivar plan_name: Plan Name. + :vartype plan_name: str + :ivar charge_type: Indicates a charge represents credits, usage, a Marketplace purchase, a + reservation fee, or a refund. + :vartype charge_type: str + :ivar frequency: Indicates how frequently this charge will occur. OneTime for purchases which + only happen once, Monthly for fees which recur every month, and UsageBased for charges based on + how much a service is used. + :vartype frequency: str + :ivar pay_g_price: Retail price for the resource. + :vartype pay_g_price: ~decimal.Decimal + :ivar benefit_id: Unique identifier for the applicable benefit. + :vartype benefit_id: str + :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", and "Spot". + :vartype pricing_model: str or ~azure.mgmt.consumption.models.PricingModelType + """ + + billing_account_id: Optional[str] = rest_field(name="billingAccountId", visibility=["read"]) + """Billing Account identifier.""" + billing_account_name: Optional[str] = rest_field(name="billingAccountName", visibility=["read"]) + """Billing Account Name.""" + billing_period_start_date: Optional[datetime.datetime] = rest_field( + name="billingPeriodStartDate", visibility=["read"], format="rfc3339" + ) + """The billing period start date.""" + billing_period_end_date: Optional[datetime.datetime] = rest_field( + name="billingPeriodEndDate", visibility=["read"], format="rfc3339" + ) + """The billing period end date.""" + billing_profile_id: Optional[str] = rest_field(name="billingProfileId", visibility=["read"]) + """Billing Profile identifier.""" + billing_profile_name: Optional[str] = rest_field(name="billingProfileName", visibility=["read"]) + """Billing Profile Name.""" + account_owner_id: Optional[str] = rest_field(name="accountOwnerId", visibility=["read"]) + """Account Owner Id.""" + account_name: Optional[str] = rest_field(name="accountName", visibility=["read"]) + """Account Name.""" + subscription_id: Optional[str] = rest_field(name="subscriptionId", visibility=["read"]) + """Subscription guid.""" + subscription_name: Optional[str] = rest_field(name="subscriptionName", visibility=["read"]) + """Subscription name.""" + date: Optional[datetime.datetime] = rest_field(visibility=["read"], format="rfc3339") + """Date for the usage record.""" + product: Optional[str] = rest_field(visibility=["read"]) + """Product name for the consumed service or purchase. Not available for Marketplace.""" + part_number: Optional[str] = rest_field(name="partNumber", visibility=["read"]) + """Part Number of the service used. Can be used to join with the price sheet. Not available for + marketplace.""" + meter_id: Optional[str] = rest_field(name="meterId", visibility=["read"]) + """The meter id (GUID). Not available for marketplace. For reserved instance this represents the + primary meter for which the reservation was purchased. For the actual VM Size for which the + reservation is purchased see productOrderName.""" + meter_details: Optional["_models.MeterDetailsResponse"] = rest_field(name="meterDetails", visibility=["read"]) + """The details about the meter. By default this is not populated, unless it's specified in + $expand.""" + quantity: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The usage quantity.""" + effective_price: Optional[decimal.Decimal] = rest_field(name="effectivePrice", visibility=["read"]) + """Effective Price that's charged for the usage.""" + cost: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The amount of cost before tax.""" + unit_price: Optional[decimal.Decimal] = rest_field(name="unitPrice", visibility=["read"]) + """Unit Price is the price applicable to you. (your EA or other contract price).""" + billing_currency: Optional[str] = rest_field(name="billingCurrency", visibility=["read"]) + """Billing Currency.""" + resource_location: Optional[str] = rest_field(name="resourceLocation", visibility=["read"]) + """Resource Location.""" + consumed_service: Optional[str] = rest_field(name="consumedService", visibility=["read"]) + """Consumed service name. Name of the azure resource provider that emits the usage or was + purchased. This value is not provided for marketplace usage.""" + resource_id: Optional[str] = rest_field(name="resourceId", visibility=["read"]) + """Unique identifier of the Azure Resource Manager usage detail resource.""" + resource_name: Optional[str] = rest_field(name="resourceName", visibility=["read"]) + """Resource Name.""" + service_info1: Optional[str] = rest_field(name="serviceInfo1", visibility=["read"]) + """Service-specific metadata.""" + service_info2: Optional[str] = rest_field(name="serviceInfo2", visibility=["read"]) + """Legacy field with optional service-specific metadata.""" + additional_info: Optional[str] = rest_field(name="additionalInfo", visibility=["read"]) + """Additional details of this usage item. By default this is not populated, unless it's specified + in $expand. Use this field to get usage line item specific details such as the actual VM Size + (ServiceType) or the ratio in which the reservation discount is applied.""" + invoice_section: Optional[str] = rest_field(name="invoiceSection", visibility=["read"]) + """Invoice Section Name.""" + cost_center: Optional[str] = rest_field(name="costCenter", visibility=["read"]) + """The cost center of this department if it is a department and a cost center is provided.""" + resource_group: Optional[str] = rest_field(name="resourceGroup", visibility=["read"]) + """Resource Group Name.""" + reservation_id: Optional[str] = rest_field(name="reservationId", visibility=["read"]) + """ARM resource id of the reservation. Only applies to records relevant to reservations.""" + reservation_name: Optional[str] = rest_field(name="reservationName", visibility=["read"]) + """User provided display name of the reservation. Last known name for a particular day is + populated in the daily data. Only applies to records relevant to reservations.""" + product_order_id: Optional[str] = rest_field(name="productOrderId", visibility=["read"]) + """Product Order Id. For reservations this is the Reservation Order ID.""" + product_order_name: Optional[str] = rest_field(name="productOrderName", visibility=["read"]) + """Product Order Name. For reservations this is the SKU that was purchased.""" + offer_id: Optional[str] = rest_field(name="offerId", visibility=["read"]) + """Offer Id. Ex: MS-AZR-0017P, MS-AZR-0148P.""" + is_azure_credit_eligible: Optional[bool] = rest_field(name="isAzureCreditEligible", visibility=["read"]) + """Is Azure Credit Eligible.""" + term: Optional[str] = rest_field(visibility=["read"]) + """Term (in months). 1 month for monthly recurring purchase. 12 months for a 1 year reservation. + 36 months for a 3 year reservation.""" + publisher_name: Optional[str] = rest_field(name="publisherName", visibility=["read"]) + """Publisher Name.""" + publisher_type: Optional[str] = rest_field(name="publisherType", visibility=["read"]) + """Publisher Type.""" + plan_name: Optional[str] = rest_field(name="planName", visibility=["read"]) + """Plan Name.""" + charge_type: Optional[str] = rest_field(name="chargeType", visibility=["read"]) + """Indicates a charge represents credits, usage, a Marketplace purchase, a reservation fee, or a + refund.""" + frequency: Optional[str] = rest_field(visibility=["read"]) + """Indicates how frequently this charge will occur. OneTime for purchases which only happen once, + Monthly for fees which recur every month, and UsageBased for charges based on how much a + service is used.""" + pay_g_price: Optional[decimal.Decimal] = rest_field(name="payGPrice", visibility=["read"]) + """Retail price for the resource.""" + benefit_id: Optional[str] = rest_field(name="benefitId", visibility=["read"]) + """Unique identifier for the applicable benefit.""" + benefit_name: Optional[str] = rest_field(name="benefitName", visibility=["read"]) + """Name of the applicable benefit.""" + pricing_model: Optional[Union[str, "_models.PricingModelType"]] = rest_field( + name="pricingModel", visibility=["read"] + ) + """Identifier that indicates how the meter is priced. Known values are: \"On Demand\", + \"Reservation\", and \"Spot\".""" + + +class LotProperties(_Model): + """The lot properties. + + :ivar original_amount: The original amount of a lot, Note: This will not be returned for + Contributor Organization Type in Multi-Entity consumption commitment. + :vartype original_amount: ~azure.mgmt.consumption.models.Amount + :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", + 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 + :ivar expiration_date: The expiration date of a lot. + :vartype expiration_date: ~datetime.datetime + :ivar po_number: The po number of the invoice on which the lot was added. This property is not + available for ConsumptionCommitment lots. + :vartype po_number: str + :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", and "Canceled". + :vartype status: str or ~azure.mgmt.consumption.models.Status + :ivar credit_currency: The currency of the lot. + :vartype credit_currency: str + :ivar billing_currency: The billing currency of the lot. + :vartype billing_currency: str + :ivar original_amount_in_billing_currency: The original amount of a lot in billing currency, + Note: This will not be returned for Contributor Organization Type in Multi-Entity consumption + commitment. + :vartype original_amount_in_billing_currency: + ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar closed_balance_in_billing_currency: The balance as of the last invoice in billing + currency. + :vartype closed_balance_in_billing_currency: + ~azure.mgmt.consumption.models.AmountWithExchangeRate + :ivar reseller: The reseller of the lot. + :vartype reseller: ~azure.mgmt.consumption.models.Reseller + :ivar is_estimated_balance: If true, the listed details are based on an estimation and it will + be subjected to change. + :vartype is_estimated_balance: bool + :ivar e_tag: The eTag for the resource. + :vartype e_tag: str + :ivar organization_type: The organization type of the lot. Known values are: "Primary" and + "Contributor". + :vartype organization_type: str or ~azure.mgmt.consumption.models.OrganizationType + :ivar used_amount: Amount consumed from the commitment. + :vartype used_amount: ~azure.mgmt.consumption.models.Amount + """ + + original_amount: Optional["_models.Amount"] = rest_field(name="originalAmount", visibility=["read"]) + """The original amount of a lot, Note: This will not be returned for Contributor Organization Type + in Multi-Entity consumption commitment.""" + closed_balance: Optional["_models.Amount"] = rest_field(name="closedBalance", visibility=["read"]) + """The balance as of the last invoice.""" + source: Optional[Union[str, "_models.LotSource"]] = rest_field(visibility=["read"]) + """The source of the lot. Known values are: \"PurchasedCredit\", \"PromotionalCredit\", and + \"ConsumptionCommitment\".""" + start_date: Optional[datetime.datetime] = rest_field(name="startDate", visibility=["read"], format="rfc3339") + """The date when the lot became effective.""" + expiration_date: Optional[datetime.datetime] = rest_field( + name="expirationDate", visibility=["read"], format="rfc3339" + ) + """The expiration date of a lot.""" + po_number: Optional[str] = rest_field(name="poNumber", visibility=["read"]) + """The po number of the invoice on which the lot was added. This property is not available for + ConsumptionCommitment lots.""" + purchased_date: Optional[datetime.datetime] = rest_field( + name="purchasedDate", visibility=["read"], format="rfc3339" + ) + """The date when the lot was added.""" + status: Optional[Union[str, "_models.Status"]] = rest_field(visibility=["read"]) + """The status of the lot. Known values are: \"None\", \"Active\", \"Inactive\", \"Expired\", + \"Complete\", and \"Canceled\".""" + credit_currency: Optional[str] = rest_field(name="creditCurrency", visibility=["read"]) + """The currency of the lot.""" + billing_currency: Optional[str] = rest_field(name="billingCurrency", visibility=["read"]) + """The billing currency of the lot.""" + original_amount_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="originalAmountInBillingCurrency", visibility=["read"] + ) + """The original amount of a lot in billing currency, Note: This will not be returned for + Contributor Organization Type in Multi-Entity consumption commitment.""" + closed_balance_in_billing_currency: Optional["_models.AmountWithExchangeRate"] = rest_field( + name="closedBalanceInBillingCurrency", visibility=["read"] + ) + """The balance as of the last invoice in billing currency.""" + reseller: Optional["_models.Reseller"] = rest_field(visibility=["read"]) + """The reseller of the lot.""" + is_estimated_balance: Optional[bool] = rest_field(name="isEstimatedBalance", visibility=["read"]) + """If true, the listed details are based on an estimation and it will be subjected to change.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read"]) + """The eTag for the resource.""" + organization_type: Optional[Union[str, "_models.OrganizationType"]] = rest_field( + name="OrganizationType", visibility=["read"] + ) + """The organization type of the lot. Known values are: \"Primary\" and \"Contributor\".""" + used_amount: Optional["_models.Amount"] = rest_field(name="usedAmount", visibility=["read"]) + """Amount consumed from the commitment.""" + + +class LotSummary(ProxyResource): + """A lot summary resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The lot properties. + :vartype properties: ~azure.mgmt.consumption.models.LotProperties + :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 + """ + + properties: Optional["_models.LotProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The lot properties.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """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.""" + + __flattened_items = [ + "original_amount", + "closed_balance", + "source", + "start_date", + "expiration_date", + "po_number", + "purchased_date", + "status", + "credit_currency", + "billing_currency", + "original_amount_in_billing_currency", + "closed_balance_in_billing_currency", + "reseller", + "is_estimated_balance", + "e_tag", + "organization_type", + "used_amount", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.LotProperties"] = None, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ManagementGroupAggregatedCostProperties(_Model): + """The properties of the Management Group Aggregated Cost. + + :ivar billing_period_id: The id of the billing period resource that the aggregated cost belongs + to. + :vartype billing_period_id: str + :ivar usage_start: The start of the date time range covered by aggregated cost. + :vartype usage_start: ~datetime.datetime + :ivar usage_end: The end of the date time range covered by the aggregated cost. + :vartype usage_end: ~datetime.datetime + :ivar azure_charges: Azure Charges. + :vartype azure_charges: ~decimal.Decimal + :ivar marketplace_charges: Marketplace Charges. + :vartype marketplace_charges: ~decimal.Decimal + :ivar charges_billed_separately: Charges Billed Separately. + :vartype charges_billed_separately: ~decimal.Decimal + :ivar currency: The ISO currency in which the meter is charged, for example, USD. + :vartype currency: str + :ivar children: Children of a management group. + :vartype children: list[~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult] + :ivar included_subscriptions: List of subscription Guids included in the calculation of + aggregated cost. + :vartype included_subscriptions: list[str] + :ivar excluded_subscriptions: List of subscription Guids excluded from the calculation of + aggregated cost. + :vartype excluded_subscriptions: list[str] + """ + + billing_period_id: Optional[str] = rest_field(name="billingPeriodId", visibility=["read"]) + """The id of the billing period resource that the aggregated cost belongs to.""" + usage_start: Optional[datetime.datetime] = rest_field(name="usageStart", visibility=["read"], format="rfc3339") + """The start of the date time range covered by aggregated cost.""" + usage_end: Optional[datetime.datetime] = rest_field(name="usageEnd", visibility=["read"], format="rfc3339") + """The end of the date time range covered by the aggregated cost.""" + azure_charges: Optional[decimal.Decimal] = rest_field(name="azureCharges", visibility=["read"]) + """Azure Charges.""" + marketplace_charges: Optional[decimal.Decimal] = rest_field(name="marketplaceCharges", visibility=["read"]) + """Marketplace Charges.""" + charges_billed_separately: Optional[decimal.Decimal] = rest_field( + name="chargesBilledSeparately", visibility=["read"] + ) + """Charges Billed Separately.""" + currency: Optional[str] = rest_field(visibility=["read"]) + """The ISO currency in which the meter is charged, for example, USD.""" + children: Optional[list["_models.ManagementGroupAggregatedCostResult"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Children of a management group.""" + included_subscriptions: Optional[list[str]] = rest_field( + name="includedSubscriptions", visibility=["read", "create", "update", "delete", "query"] + ) + """List of subscription Guids included in the calculation of aggregated cost.""" + excluded_subscriptions: Optional[list[str]] = rest_field( + name="excludedSubscriptions", visibility=["read", "create", "update", "delete", "query"] + ) + """List of subscription Guids excluded from the calculation of aggregated cost.""" + + @overload + def __init__( + self, + *, + children: Optional[list["_models.ManagementGroupAggregatedCostResult"]] = None, + included_subscriptions: Optional[list[str]] = None, + excluded_subscriptions: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ManagementGroupAggregatedCostResult(Resource): + """A management group aggregated cost resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the Management Group Aggregated Cost. + :vartype properties: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostProperties + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + properties: Optional["_models.ManagementGroupAggregatedCostProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the Management Group Aggregated Cost.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = [ + "billing_period_id", + "usage_start", + "usage_end", + "azure_charges", + "marketplace_charges", + "charges_billed_separately", + "currency", + "children", + "included_subscriptions", + "excluded_subscriptions", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.ManagementGroupAggregatedCostProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class Marketplace(Resource): + """A marketplace resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the marketplace usage detail. + :vartype properties: ~azure.mgmt.consumption.models.MarketplaceProperties + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + properties: Optional["_models.MarketplaceProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the marketplace usage detail.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = [ + "billing_period_id", + "usage_start", + "usage_end", + "resource_rate", + "offer_name", + "resource_group", + "additional_info", + "order_number", + "instance_name", + "instance_id", + "currency", + "consumed_quantity", + "unit_of_measure", + "pretax_cost", + "is_estimated", + "meter_id", + "subscription_guid", + "subscription_name", + "account_name", + "department_name", + "consumed_service", + "cost_center", + "additional_properties", + "publisher_name", + "plan_name", + "is_recurring_charge", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.MarketplaceProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class MarketplaceProperties(_Model): + """The properties of the marketplace usage detail. + + :ivar billing_period_id: The id of the billing period resource that the usage belongs to. + :vartype billing_period_id: str + :ivar usage_start: The start of the date time range covered by the usage detail. + :vartype usage_start: ~datetime.datetime + :ivar usage_end: The end of the date time range covered by the usage detail. + :vartype usage_end: ~datetime.datetime + :ivar resource_rate: The marketplace resource rate. + :vartype resource_rate: ~decimal.Decimal + :ivar offer_name: The type of offer. + :vartype offer_name: str + :ivar resource_group: The name of resource group. + :vartype resource_group: str + :ivar additional_info: Additional information. + :vartype additional_info: str + :ivar order_number: The order number. + :vartype order_number: str + :ivar instance_name: The name of the resource instance that the usage is about. + :vartype instance_name: str + :ivar instance_id: The uri of the resource instance that the usage is about. + :vartype instance_id: str + :ivar currency: The ISO currency in which the meter is charged, for example, USD. + :vartype currency: str + :ivar consumed_quantity: The quantity of usage. + :vartype consumed_quantity: ~decimal.Decimal + :ivar unit_of_measure: The unit of measure. + :vartype unit_of_measure: str + :ivar pretax_cost: The amount of cost before tax. + :vartype pretax_cost: ~decimal.Decimal + :ivar is_estimated: The estimated usage is subject to change. + :vartype is_estimated: bool + :ivar meter_id: The meter id (GUID). + :vartype meter_id: str + :ivar subscription_guid: Subscription guid. + :vartype subscription_guid: str + :ivar subscription_name: Subscription name. + :vartype subscription_name: str + :ivar account_name: Account name. + :vartype account_name: str + :ivar department_name: Department name. + :vartype department_name: str + :ivar consumed_service: Consumed service name. + :vartype consumed_service: str + :ivar cost_center: The cost center of this department if it is a department and a costcenter + exists. + :vartype cost_center: str + :ivar additional_properties: Additional details of this usage item. By default this is not + populated, unless it's specified in $expand. + :vartype additional_properties: str + :ivar publisher_name: The name of publisher. + :vartype publisher_name: str + :ivar plan_name: The name of plan. + :vartype plan_name: str + :ivar is_recurring_charge: Flag indicating whether this is a recurring charge or not. + :vartype is_recurring_charge: bool + """ + + billing_period_id: Optional[str] = rest_field(name="billingPeriodId", visibility=["read"]) + """The id of the billing period resource that the usage belongs to.""" + usage_start: Optional[datetime.datetime] = rest_field(name="usageStart", visibility=["read"], format="rfc3339") + """The start of the date time range covered by the usage detail.""" + usage_end: Optional[datetime.datetime] = rest_field(name="usageEnd", visibility=["read"], format="rfc3339") + """The end of the date time range covered by the usage detail.""" + resource_rate: Optional[decimal.Decimal] = rest_field(name="resourceRate", visibility=["read"]) + """The marketplace resource rate.""" + offer_name: Optional[str] = rest_field(name="offerName", visibility=["read"]) + """The type of offer.""" + resource_group: Optional[str] = rest_field(name="resourceGroup", visibility=["read"]) + """The name of resource group.""" + additional_info: Optional[str] = rest_field(name="additionalInfo", visibility=["read"]) + """Additional information.""" + order_number: Optional[str] = rest_field(name="orderNumber", visibility=["read"]) + """The order number.""" + instance_name: Optional[str] = rest_field(name="instanceName", visibility=["read"]) + """The name of the resource instance that the usage is about.""" + instance_id: Optional[str] = rest_field(name="instanceId", visibility=["read"]) + """The uri of the resource instance that the usage is about.""" + currency: Optional[str] = rest_field(visibility=["read"]) + """The ISO currency in which the meter is charged, for example, USD.""" + consumed_quantity: Optional[decimal.Decimal] = rest_field(name="consumedQuantity", visibility=["read"]) + """The quantity of usage.""" + unit_of_measure: Optional[str] = rest_field(name="unitOfMeasure", visibility=["read"]) + """The unit of measure.""" + pretax_cost: Optional[decimal.Decimal] = rest_field(name="pretaxCost", visibility=["read"]) + """The amount of cost before tax.""" + is_estimated: Optional[bool] = rest_field(name="isEstimated", visibility=["read"]) + """The estimated usage is subject to change.""" + meter_id: Optional[str] = rest_field(name="meterId", visibility=["read"]) + """The meter id (GUID).""" + subscription_guid: Optional[str] = rest_field(name="subscriptionGuid", visibility=["read"]) + """Subscription guid.""" + subscription_name: Optional[str] = rest_field(name="subscriptionName", visibility=["read"]) + """Subscription name.""" + account_name: Optional[str] = rest_field(name="accountName", visibility=["read"]) + """Account name.""" + department_name: Optional[str] = rest_field(name="departmentName", visibility=["read"]) + """Department name.""" + consumed_service: Optional[str] = rest_field(name="consumedService", visibility=["read"]) + """Consumed service name.""" + cost_center: Optional[str] = rest_field(name="costCenter", visibility=["read"]) + """The cost center of this department if it is a department and a costcenter exists.""" + additional_properties: Optional[str] = rest_field(name="additionalProperties", visibility=["read"]) + """Additional details of this usage item. By default this is not populated, unless it's specified + in $expand.""" + publisher_name: Optional[str] = rest_field(name="publisherName", visibility=["read"]) + """The name of publisher.""" + plan_name: Optional[str] = rest_field(name="planName", visibility=["read"]) + """The name of plan.""" + is_recurring_charge: Optional[bool] = rest_field(name="isRecurringCharge", visibility=["read"]) + """Flag indicating whether this is a recurring charge or not.""" + + +class MeterDetails(_Model): + """The properties of the meter detail. + + :ivar meter_name: The name of the meter, within the given meter category. + :vartype meter_name: str + :ivar meter_category: The category of the meter, for example, 'Cloud services', 'Networking', + etc.. + :vartype meter_category: str + :ivar meter_sub_category: The subcategory of the meter, for example, 'A6 Cloud services', + 'ExpressRoute (IXP)', etc.. + :vartype meter_sub_category: str + :ivar unit: The unit in which the meter consumption is charged, for example, 'Hours', 'GB', + etc. + :vartype unit: str + :ivar meter_location: The location in which the Azure service is available. + :vartype meter_location: str + :ivar total_included_quantity: The total included quantity associated with the offer. + :vartype total_included_quantity: ~decimal.Decimal + :ivar pretax_standard_rate: The pretax listing price. + :vartype pretax_standard_rate: ~decimal.Decimal + :ivar service_name: The name of the service. + :vartype service_name: str + :ivar service_tier: The service tier. + :vartype service_tier: str + """ + + meter_name: Optional[str] = rest_field(name="meterName", visibility=["read"]) + """The name of the meter, within the given meter category.""" + meter_category: Optional[str] = rest_field(name="meterCategory", visibility=["read"]) + """The category of the meter, for example, 'Cloud services', 'Networking', etc..""" + meter_sub_category: Optional[str] = rest_field(name="meterSubCategory", visibility=["read"]) + """The subcategory of the meter, for example, 'A6 Cloud services', 'ExpressRoute (IXP)', etc..""" + unit: Optional[str] = rest_field(visibility=["read"]) + """The unit in which the meter consumption is charged, for example, 'Hours', 'GB', etc.""" + meter_location: Optional[str] = rest_field(name="meterLocation", visibility=["read"]) + """The location in which the Azure service is available.""" + total_included_quantity: Optional[decimal.Decimal] = rest_field(name="totalIncludedQuantity", visibility=["read"]) + """The total included quantity associated with the offer.""" + pretax_standard_rate: Optional[decimal.Decimal] = rest_field(name="pretaxStandardRate", visibility=["read"]) + """The pretax listing price.""" + service_name: Optional[str] = rest_field(name="serviceName", visibility=["read"]) + """The name of the service.""" + service_tier: Optional[str] = rest_field(name="serviceTier", visibility=["read"]) + """The service tier.""" + + +class MeterDetailsResponse(_Model): + """The properties of the meter detail. + + :ivar meter_name: The name of the meter, within the given meter category. + :vartype meter_name: str + :ivar meter_category: The category of the meter, for example, 'Cloud services', 'Networking', + etc.. + :vartype meter_category: str + :ivar meter_sub_category: The subcategory of the meter, for example, 'A6 Cloud services', + 'ExpressRoute (IXP)', etc.. + :vartype meter_sub_category: str + :ivar unit_of_measure: The unit in which the meter consumption is charged, for example, + 'Hours', 'GB', etc. + :vartype unit_of_measure: str + :ivar service_family: The service family. + :vartype service_family: str + """ + + meter_name: Optional[str] = rest_field(name="meterName", visibility=["read"]) + """The name of the meter, within the given meter category.""" + meter_category: Optional[str] = rest_field(name="meterCategory", visibility=["read"]) + """The category of the meter, for example, 'Cloud services', 'Networking', etc..""" + meter_sub_category: Optional[str] = rest_field(name="meterSubCategory", visibility=["read"]) + """The subcategory of the meter, for example, 'A6 Cloud services', 'ExpressRoute (IXP)', etc..""" + unit_of_measure: Optional[str] = rest_field(name="unitOfMeasure", visibility=["read"]) + """The unit in which the meter consumption is charged, for example, 'Hours', 'GB', etc.""" + service_family: Optional[str] = rest_field(name="serviceFamily", visibility=["read"]) + """The service family.""" + + +class ModernChargeSummary(ChargeSummary, discriminator="modern"): + """Modern charge summary. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :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 properties: Properties for modern charge summary. Required. + :vartype properties: ~azure.mgmt.consumption.models.ModernChargeSummaryProperties + :ivar kind: Specifies the kind of charge summary. Required. MODERN. + :vartype kind: str or ~azure.mgmt.consumption.models.MODERN + """ + + properties: "_models.ModernChargeSummaryProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for modern charge summary. Required.""" + kind: Literal[ChargeSummaryKind.MODERN] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Specifies the kind of charge summary. Required. MODERN.""" + + __flattened_items = [ + "billing_period_id", + "usage_start", + "usage_end", + "azure_charges", + "charges_billed_separately", + "marketplace_charges", + "billing_account_id", + "billing_profile_id", + "invoice_section_id", + "customer_id", + "is_invoiced", + "subscription_id", + ] + + @overload + def __init__( + self, + *, + properties: "_models.ModernChargeSummaryProperties", + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ModernChargeSummaryProperties(_Model): + """The properties of modern charge summary. + + :ivar billing_period_id: The id of the billing period resource that the charge belongs to. + :vartype billing_period_id: str + :ivar usage_start: Usage start date. + :vartype usage_start: str + :ivar usage_end: Usage end date. + :vartype usage_end: str + :ivar azure_charges: Azure Charges. + :vartype azure_charges: ~azure.mgmt.consumption.models.Amount + :ivar charges_billed_separately: Charges Billed separately. + :vartype charges_billed_separately: ~azure.mgmt.consumption.models.Amount + :ivar marketplace_charges: Marketplace Charges. + :vartype marketplace_charges: ~azure.mgmt.consumption.models.Amount + :ivar billing_account_id: Billing Account Id. + :vartype billing_account_id: str + :ivar billing_profile_id: Billing Profile Id. + :vartype billing_profile_id: str + :ivar invoice_section_id: Invoice Section Id. + :vartype invoice_section_id: str + :ivar customer_id: Customer Id. + :vartype customer_id: str + :ivar is_invoiced: Is charge Invoiced. + :vartype is_invoiced: bool + :ivar subscription_id: Subscription guid. + :vartype subscription_id: str + """ + + billing_period_id: Optional[str] = rest_field(name="billingPeriodId", visibility=["read"]) + """The id of the billing period resource that the charge belongs to.""" + usage_start: Optional[str] = rest_field(name="usageStart", visibility=["read"]) + """Usage start date.""" + usage_end: Optional[str] = rest_field(name="usageEnd", visibility=["read"]) + """Usage end date.""" + azure_charges: Optional["_models.Amount"] = rest_field(name="azureCharges", visibility=["read"]) + """Azure Charges.""" + charges_billed_separately: Optional["_models.Amount"] = rest_field( + name="chargesBilledSeparately", visibility=["read"] + ) + """Charges Billed separately.""" + marketplace_charges: Optional["_models.Amount"] = rest_field(name="marketplaceCharges", visibility=["read"]) + """Marketplace Charges.""" + billing_account_id: Optional[str] = rest_field(name="billingAccountId", visibility=["read"]) + """Billing Account Id.""" + billing_profile_id: Optional[str] = rest_field(name="billingProfileId", visibility=["read"]) + """Billing Profile Id.""" + invoice_section_id: Optional[str] = rest_field(name="invoiceSectionId", visibility=["read"]) + """Invoice Section Id.""" + customer_id: Optional[str] = rest_field(name="customerId", visibility=["read"]) + """Customer Id.""" + is_invoiced: Optional[bool] = rest_field(name="isInvoiced", visibility=["read"]) + """Is charge Invoiced.""" + subscription_id: Optional[str] = rest_field(name="subscriptionId", visibility=["read"]) + """Subscription guid.""" + + +class ModernReservationRecommendation(ReservationRecommendation, discriminator="modern"): + """Modern reservation recommendation. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar location: Resource location. + :vartype location: str + :ivar sku: Resource sku. + :vartype sku: str + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties for modern reservation recommendation. Required. + :vartype properties: ~azure.mgmt.consumption.models.ModernReservationRecommendationProperties + :ivar kind: Specifies the kind of reservation recommendation. Required. MODERN. + :vartype kind: str or ~azure.mgmt.consumption.models.MODERN + """ + + properties: "_models.ModernReservationRecommendationProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for modern reservation recommendation. Required.""" + kind: Literal[ReservationRecommendationKind.MODERN] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Specifies the kind of reservation recommendation. Required. MODERN.""" + + @overload + def __init__( + self, + *, + properties: "_models.ModernReservationRecommendationProperties", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = ReservationRecommendationKind.MODERN # type: ignore + + +class ModernReservationRecommendationProperties(_Model): # pylint: disable=name-too-long + """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 + + :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: Term period of the reservation. ex: P1M, P1Y or P3Y. + :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: ~decimal.Decimal + :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. Default value is None. + :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 last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int + """ + + __mapping__: dict[str, _Model] = {} + location: Optional[str] = rest_field(visibility=["read"]) + """Resource Location.""" + look_back_period: Optional[int] = rest_field(name="lookBackPeriod", visibility=["read"]) + """The number of days of usage to look back for recommendation.""" + instance_flexibility_ratio: Optional[float] = rest_field(name="instanceFlexibilityRatio", visibility=["read"]) + """The instance Flexibility Ratio.""" + instance_flexibility_group: Optional[str] = rest_field(name="instanceFlexibilityGroup", visibility=["read"]) + """The instance Flexibility Group.""" + normalized_size: Optional[str] = rest_field(name="normalizedSize", visibility=["read"]) + """The normalized Size.""" + recommended_quantity_normalized: Optional[float] = rest_field( + name="recommendedQuantityNormalized", visibility=["read"] + ) + """The recommended Quantity Normalized.""" + meter_id: Optional[str] = rest_field(name="meterId", visibility=["read"]) + """The meter id (GUID).""" + term: Optional[str] = rest_field(visibility=["read"]) + """Term period of the reservation. ex: P1M, P1Y or P3Y.""" + cost_with_no_reserved_instances: Optional["_models.Amount"] = rest_field( + name="costWithNoReservedInstances", visibility=["read"] + ) + """The total amount of cost without reserved instances.""" + recommended_quantity: Optional[decimal.Decimal] = rest_field(name="recommendedQuantity", visibility=["read"]) + """Recommended quality for reserved instances.""" + resource_type: Optional[str] = rest_field(name="resourceType", visibility=["read"]) + """Resource type.""" + total_cost_with_reserved_instances: Optional["_models.Amount"] = rest_field( + name="totalCostWithReservedInstances", visibility=["read"] + ) + """The total amount of cost with reserved instances.""" + net_savings: Optional["_models.Amount"] = rest_field(name="netSavings", visibility=["read"]) + """Total estimated savings with reserved instances.""" + first_usage_date: Optional[datetime.datetime] = rest_field( + name="firstUsageDate", visibility=["read"], format="rfc3339" + ) + """The usage date for looking back.""" + scope: str = rest_discriminator(name="scope", visibility=["read", "create", "update", "delete", "query"]) + """Shared or single recommendation. Required. Default value is None.""" + sku_properties: Optional[list["_models.SkuProperty"]] = rest_field(name="skuProperties", visibility=["read"]) + """List of sku properties.""" + sku_name: Optional[str] = rest_field(name="skuName", visibility=["read"]) + """This is the ARM Sku name.""" + last_usage_date: Optional[datetime.datetime] = rest_field( + name="lastUsageDate", visibility=["read"], format="rfc3339" + ) + """The last usage date used for looking back for computing the recommendation.""" + total_hours: Optional[int] = rest_field(name="totalHours", visibility=["read"]) + """The total hours for which the cost is covered.""" + + @overload + def __init__( + self, + *, + scope: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ModernReservationTransaction(Resource): + """Modern Reservation transaction resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of a modern reservation transaction. Required. + :vartype properties: ~azure.mgmt.consumption.models.ModernReservationTransactionProperties + :ivar tags: Resource tags. + :vartype tags: list[str] + """ + + properties: "_models.ModernReservationTransactionProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of a modern reservation transaction. Required.""" + tags: Optional[list[str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = [ + "amount", + "arm_sku_name", + "billing_frequency", + "billing_profile_id", + "billing_profile_name", + "currency", + "description", + "event_date", + "event_type", + "invoice", + "invoice_id", + "invoice_section_id", + "invoice_section_name", + "purchasing_subscription_guid", + "purchasing_subscription_name", + "quantity", + "region", + "reservation_order_id", + "reservation_order_name", + "term", + ] + + @overload + def __init__( + self, + *, + properties: "_models.ModernReservationTransactionProperties", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ModernReservationTransactionProperties(_Model): + """The properties of a modern reservation transaction. + + :ivar amount: The charge of the transaction. + :vartype amount: ~decimal.Decimal + :ivar arm_sku_name: This is the ARM Sku name. It can be used to join with the serviceType field + in additional info in usage records. + :vartype arm_sku_name: str + :ivar billing_frequency: The billing frequency, which can be either one-time or recurring. + :vartype billing_frequency: str + :ivar billing_profile_id: Billing profile Id. + :vartype billing_profile_id: str + :ivar billing_profile_name: Billing profile name. + :vartype billing_profile_name: str + :ivar currency: The ISO currency in which the transaction is charged, for example, USD. + :vartype currency: str + :ivar description: The description of the transaction. + :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 or Refund). + :vartype event_type: str + :ivar invoice: Invoice Number. + :vartype invoice: str + :ivar invoice_id: Invoice Id as on the invoice where the specific transaction appears. + :vartype invoice_id: str + :ivar invoice_section_id: Invoice Section Id. + :vartype invoice_section_id: str + :ivar invoice_section_name: Invoice Section Name. + :vartype invoice_section_name: str + :ivar purchasing_subscription_guid: The subscription guid that makes the transaction. + :vartype purchasing_subscription_guid: str + :ivar purchasing_subscription_name: The subscription name that makes the transaction. + :vartype purchasing_subscription_name: str + :ivar quantity: The quantity of the transaction. + :vartype quantity: ~decimal.Decimal + :ivar region: The region of the transaction. + :vartype region: 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 + order contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype reservation_order_id: str + :ivar reservation_order_name: The name of the reservation order. + :vartype reservation_order_name: str + :ivar term: This is the term of the transaction. + :vartype term: str + """ + + amount: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The charge of the transaction.""" + arm_sku_name: Optional[str] = rest_field(name="armSkuName", visibility=["read"]) + """This is the ARM Sku name. It can be used to join with the serviceType field in additional info + in usage records.""" + billing_frequency: Optional[str] = rest_field(name="billingFrequency", visibility=["read"]) + """The billing frequency, which can be either one-time or recurring.""" + billing_profile_id: Optional[str] = rest_field(name="billingProfileId", visibility=["read"]) + """Billing profile Id.""" + billing_profile_name: Optional[str] = rest_field(name="billingProfileName", visibility=["read"]) + """Billing profile name.""" + currency: Optional[str] = rest_field(visibility=["read"]) + """The ISO currency in which the transaction is charged, for example, USD.""" + description: Optional[str] = rest_field(visibility=["read"]) + """The description of the transaction.""" + event_date: Optional[datetime.datetime] = rest_field(name="eventDate", visibility=["read"], format="rfc3339") + """The date of the transaction.""" + event_type: Optional[str] = rest_field(name="eventType", visibility=["read"]) + """The type of the transaction (Purchase, Cancel or Refund).""" + invoice: Optional[str] = rest_field(visibility=["read"]) + """Invoice Number.""" + invoice_id: Optional[str] = rest_field(name="invoiceId", visibility=["read"]) + """Invoice Id as on the invoice where the specific transaction appears.""" + invoice_section_id: Optional[str] = rest_field(name="invoiceSectionId", visibility=["read"]) + """Invoice Section Id.""" + invoice_section_name: Optional[str] = rest_field(name="invoiceSectionName", visibility=["read"]) + """Invoice Section Name.""" + purchasing_subscription_guid: Optional[str] = rest_field(name="purchasingSubscriptionGuid", visibility=["read"]) + """The subscription guid that makes the transaction.""" + purchasing_subscription_name: Optional[str] = rest_field(name="purchasingSubscriptionName", visibility=["read"]) + """The subscription name that makes the transaction.""" + quantity: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """The quantity of the transaction.""" + region: Optional[str] = rest_field(visibility=["read"]) + """The region of the transaction.""" + reservation_order_id: Optional[str] = rest_field(name="reservationOrderId", visibility=["read"]) + """The reservation order ID is the identifier for a reservation purchase. Each reservation order + ID represents a single purchase transaction. A reservation order contains reservations. The + reservation order specifies the VM size and region for the reservations.""" + reservation_order_name: Optional[str] = rest_field(name="reservationOrderName", visibility=["read"]) + """The name of the reservation order.""" + term: Optional[str] = rest_field(visibility=["read"]) + """This is the term of the transaction.""" + + +class ModernSharedScopeReservationRecommendationProperties( + ModernReservationRecommendationProperties, discriminator="Shared" +): # pylint: disable=name-too-long + """The properties of the modern reservation recommendation for shared scope. + + :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: Term period of the reservation. ex: P1M, P1Y or P3Y. + :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: ~decimal.Decimal + :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 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 last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int + :ivar scope: Shared or single recommendation. Required. Default value is "Shared". + :vartype scope: str + """ + + scope: Literal["Shared"] = rest_discriminator(name="scope", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Shared or single recommendation. Required. Default value is \"Shared\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.scope = "Shared" # type: ignore + + +class ModernSingleScopeReservationRecommendationProperties( + ModernReservationRecommendationProperties, discriminator="Single" +): # pylint: disable=name-too-long + """The properties of the modern reservation recommendation for single scope. + + :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: Term period of the reservation. ex: P1M, P1Y or P3Y. + :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: ~decimal.Decimal + :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 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 last_usage_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_usage_date: ~datetime.datetime + :ivar total_hours: The total hours for which the cost is covered. + :vartype total_hours: int + :ivar subscription_id: Subscription ID associated with single scoped recommendation. + :vartype subscription_id: str + :ivar scope: Shared or single recommendation. Required. Default value is "Single". + :vartype scope: str + """ + + subscription_id: Optional[str] = rest_field(name="subscriptionId", visibility=["read"]) + """Subscription ID associated with single scoped recommendation.""" + scope: Literal["Single"] = rest_discriminator(name="scope", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Shared or single recommendation. Required. Default value is \"Single\".""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.scope = "Single" # type: ignore + + +class ModernUsageDetail(UsageDetail, discriminator="modern"): + """Modern usage detail. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar properties: Properties for modern usage details. Required. + :vartype properties: ~azure.mgmt.consumption.models.ModernUsageDetailProperties + :ivar kind: Specifies the kind of usage details. Required. MODERN. + :vartype kind: str or ~azure.mgmt.consumption.models.MODERN + """ + + properties: "_models.ModernUsageDetailProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for modern usage details. Required.""" + kind: Literal[UsageDetailsKind.MODERN] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Specifies the kind of usage details. Required. MODERN.""" + + __flattened_items = [ + "billing_account_id", + "effective_price", + "pricing_model", + "billing_account_name", + "billing_period_start_date", + "billing_period_end_date", + "billing_profile_id", + "billing_profile_name", + "subscription_guid", + "subscription_name", + "date", + "product", + "meter_id", + "meter_name", + "meter_region", + "meter_category", + "meter_sub_category", + "service_family", + "quantity", + "unit_of_measure", + "instance_name", + "cost_in_usd", + "unit_price", + "billing_currency_code", + "resource_location", + "consumed_service", + "service_info1", + "service_info2", + "additional_info", + "invoice_section_id", + "invoice_section_name", + "cost_center", + "resource_group", + "reservation_id", + "reservation_name", + "product_order_id", + "product_order_name", + "is_azure_credit_eligible", + "term", + "publisher_name", + "publisher_type", + "charge_type", + "frequency", + "cost_in_billing_currency", + "cost_in_pricing_currency", + "exchange_rate", + "exchange_rate_date", + "invoice_id", + "previous_invoice_id", + "pricing_currency_code", + "product_identifier", + "resource_location_normalized", + "service_period_start_date", + "service_period_end_date", + "customer_tenant_id", + "customer_name", + "partner_tenant_id", + "partner_name", + "reseller_mpn_id", + "reseller_name", + "publisher_id", + "market_price", + "exchange_rate_pricing_to_billing", + "payg_cost_in_billing_currency", + "payg_cost_in_usd", + "partner_earned_credit_rate", + "partner_earned_credit_applied", + "pay_g_price", + "benefit_id", + "benefit_name", + "provider", + "cost_allocation_rule_name", + ] + + @overload + def __init__( + self, + *, + properties: "_models.ModernUsageDetailProperties", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ModernUsageDetailProperties(_Model): + """The properties of the usage detail. + + :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: ~decimal.Decimal + :ivar pricing_model: Identifier that indicates how the meter is priced. Known values are: "On + 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 + :ivar billing_period_start_date: Billing Period Start Date as in the invoice. + :vartype billing_period_start_date: ~datetime.datetime + :ivar billing_period_end_date: Billing Period End Date as in the invoice. + :vartype billing_period_end_date: ~datetime.datetime + :ivar billing_profile_id: Identifier for the billing profile that groups costs across invoices + in the a singular billing currency across across the customers who have onboarded the Microsoft + customer agreement and the customers in CSP who have made entitlement purchases like SaaS, + Marketplace, RI, etc. + :vartype billing_profile_id: str + :ivar billing_profile_name: Name of the billing profile that groups costs across invoices in + the a singular billing currency across across the customers who have onboarded the Microsoft + customer agreement and the customers in CSP who have made entitlement purchases like SaaS, + Marketplace, RI, etc. + :vartype billing_profile_name: str + :ivar subscription_guid: Unique Microsoft generated identifier for the Azure Subscription. + :vartype subscription_guid: str + :ivar subscription_name: Name of the Azure Subscription. + :vartype subscription_name: str + :ivar date: Date for the usage record. + :vartype date: ~datetime.datetime + :ivar product: Name of the product that has accrued charges by consumption or purchase as + listed in the invoice. Not available for Marketplace. + :vartype product: str + :ivar meter_id: The meter id (GUID). Not available for marketplace. For reserved instance this + represents the primary meter for which the reservation was purchased. For the actual VM Size + for which the reservation is purchased see productOrderName. + :vartype meter_id: str + :ivar meter_name: Identifies the name of the meter against which consumption is measured. + :vartype meter_name: str + :ivar meter_region: Identifies the location of the datacenter for certain services that are + priced based on datacenter location. + :vartype meter_region: str + :ivar meter_category: Identifies the top-level service for the usage. + :vartype meter_category: str + :ivar meter_sub_category: Defines the type or sub-category of Azure service that can affect the + rate. + :vartype meter_sub_category: str + :ivar service_family: List the service family for the product purchased or charged (Example: + Storage ; Compute). + :vartype service_family: str + :ivar quantity: Measure the quantity purchased or consumed.The amount of the meter used during + the billing period. + :vartype quantity: ~decimal.Decimal + :ivar unit_of_measure: Identifies the Unit that the service is charged in. For example, GB, + hours, 10,000 s. + :vartype unit_of_measure: str + :ivar instance_name: Instance Name. + :vartype instance_name: str + :ivar cost_in_usd: Estimated extendedCost or blended cost before tax in USD. + :vartype cost_in_usd: ~decimal.Decimal + :ivar unit_price: Unit Price is the price applicable to you. (your EA or other contract price). + :vartype unit_price: ~decimal.Decimal + :ivar billing_currency_code: The currency defining the billed cost. + :vartype billing_currency_code: str + :ivar resource_location: Name of the resource location. + :vartype resource_location: str + :ivar consumed_service: Consumed service name. Name of the azure resource provider that emits + the usage or was purchased. This value is not provided for marketplace usage. + :vartype consumed_service: str + :ivar service_info1: Service-specific metadata. + :vartype service_info1: str + :ivar service_info2: Legacy field with optional service-specific metadata. + :vartype service_info2: str + :ivar additional_info: Additional details of this usage item. Use this field to get usage line + item specific details such as the actual VM Size (ServiceType) or the ratio in which the + reservation discount is applied. + :vartype additional_info: str + :ivar invoice_section_id: Identifier of the project that is being charged in the invoice. Not + applicable for Microsoft Customer Agreements onboarded by partners. + :vartype invoice_section_id: str + :ivar invoice_section_name: Name of the project that is being charged in the invoice. Not + applicable for Microsoft Customer Agreements onboarded by partners. + :vartype invoice_section_name: str + :ivar cost_center: The cost center of this department if it is a department and a cost center + is provided. + :vartype cost_center: str + :ivar resource_group: Name of the Azure resource group used for cohesive lifecycle management + of resources. + :vartype resource_group: str + :ivar reservation_id: ARM resource id of the reservation. Only applies to records relevant to + reservations. + :vartype reservation_id: str + :ivar reservation_name: User provided display name of the reservation. Last known name for a + particular day is populated in the daily data. Only applies to records relevant to + reservations. + :vartype reservation_name: str + :ivar product_order_id: The identifier for the asset or Azure plan name that the subscription + belongs to. For example: Azure Plan. For reservations this is the Reservation Order ID. + :vartype product_order_id: str + :ivar product_order_name: Product Order Name. For reservations this is the SKU that was + purchased. + :vartype product_order_name: str + :ivar is_azure_credit_eligible: Determines if the cost is eligible to be paid for using Azure + credits. + :vartype is_azure_credit_eligible: bool + :ivar term: Term (in months). Displays the term for the validity of the offer. For example. In + case of reserved instances it displays 12 months for yearly term of reserved instance. For one + time purchases or recurring purchases, the terms displays 1 month; This is not applicable for + Azure consumption. + :vartype term: str + :ivar publisher_name: Name of the publisher of the service including Microsoft or Third Party + publishers. + :vartype publisher_name: str + :ivar publisher_type: Type of publisher that identifies if the publisher is first party, third + party reseller or third party agency. + :vartype publisher_type: str + :ivar charge_type: Indicates a charge represents credits, usage, a Marketplace purchase, a + reservation fee, or a refund. + :vartype charge_type: str + :ivar frequency: Indicates how frequently this charge will occur. OneTime for purchases which + only happen once, Monthly for fees which recur every month, and UsageBased for charges based on + how much a service is used. + :vartype frequency: str + :ivar cost_in_billing_currency: ExtendedCost or blended cost before tax in billed currency. + :vartype cost_in_billing_currency: ~decimal.Decimal + :ivar cost_in_pricing_currency: ExtendedCost or blended cost before tax in pricing currency to + correlate with prices. + :vartype cost_in_pricing_currency: ~decimal.Decimal + :ivar exchange_rate: Exchange rate used in conversion from pricing currency to billing + currency. + :vartype exchange_rate: str + :ivar exchange_rate_date: Date on which exchange rate used in conversion from pricing currency + to billing currency. + :vartype exchange_rate_date: ~datetime.datetime + :ivar invoice_id: Invoice ID as on the invoice where the specific transaction appears. + :vartype invoice_id: str + :ivar previous_invoice_id: Reference to an original invoice there is a refund (negative cost). + This is populated only when there is a refund. + :vartype previous_invoice_id: str + :ivar pricing_currency_code: Pricing Billing Currency. + :vartype pricing_currency_code: str + :ivar product_identifier: Identifier for the product that has accrued charges by consumption or + purchase . This is the concatenated key of productId and SkuId in partner center. + :vartype product_identifier: str + :ivar resource_location_normalized: Resource Location Normalized. + :vartype resource_location_normalized: str + :ivar service_period_start_date: Start date for the rating period when the service usage was + rated for charges. The prices for Azure services are determined for the rating period. + :vartype service_period_start_date: ~datetime.datetime + :ivar service_period_end_date: End date for the period when the service usage was rated for + charges. The prices for Azure services are determined based on the rating period. + :vartype service_period_end_date: ~datetime.datetime + :ivar customer_tenant_id: Identifier of the customer's AAD tenant. + :vartype customer_tenant_id: str + :ivar customer_name: Name of the customer's AAD tenant. + :vartype customer_name: str + :ivar partner_tenant_id: Identifier for the partner's AAD tenant. + :vartype partner_tenant_id: str + :ivar partner_name: Name of the partner' AAD tenant. + :vartype partner_name: str + :ivar reseller_mpn_id: MPNId for the reseller associated with the subscription. + :vartype reseller_mpn_id: str + :ivar reseller_name: Reseller Name. + :vartype reseller_name: str + :ivar publisher_id: Publisher Id. + :vartype publisher_id: str + :ivar market_price: Market Price that's charged for the usage. + :vartype market_price: ~decimal.Decimal + :ivar exchange_rate_pricing_to_billing: Exchange Rate from pricing currency to billing + currency. + :vartype exchange_rate_pricing_to_billing: ~decimal.Decimal + :ivar payg_cost_in_billing_currency: The amount of PayG cost before tax in billing currency. + :vartype payg_cost_in_billing_currency: ~decimal.Decimal + :ivar payg_cost_in_usd: The amount of PayG cost before tax in US Dollar currency. + :vartype payg_cost_in_usd: ~decimal.Decimal + :ivar partner_earned_credit_rate: Rate of discount applied if there is a partner earned credit + (PEC) based on partner admin link access. + :vartype partner_earned_credit_rate: ~decimal.Decimal + :ivar partner_earned_credit_applied: Flag to indicate if partner earned credit has been applied + or not. + :vartype partner_earned_credit_applied: str + :ivar pay_g_price: Retail price for the resource. + :vartype pay_g_price: ~decimal.Decimal + :ivar benefit_id: Unique identifier for the applicable benefit. + :vartype benefit_id: str + :ivar benefit_name: Name of the applicable benefit. + :vartype benefit_name: str + :ivar provider: Identifier for Product Category or Line Of Business, Ex - Azure, Microsoft 365, + AWS e.t.c. + :vartype provider: str + :ivar cost_allocation_rule_name: Name for Cost Allocation Rule. + :vartype cost_allocation_rule_name: str + """ + + billing_account_id: Optional[str] = rest_field(name="billingAccountId", visibility=["read"]) + """Billing Account identifier.""" + effective_price: Optional[decimal.Decimal] = rest_field(name="effectivePrice", visibility=["read"]) + """Effective Price that's charged for the usage.""" + pricing_model: Optional[Union[str, "_models.PricingModelType"]] = rest_field( + name="pricingModel", visibility=["read"] + ) + """Identifier that indicates how the meter is priced. Known values are: \"On Demand\", + \"Reservation\", and \"Spot\".""" + billing_account_name: Optional[str] = rest_field(name="billingAccountName", visibility=["read"]) + """Name of the Billing Account.""" + billing_period_start_date: Optional[datetime.datetime] = rest_field( + name="billingPeriodStartDate", visibility=["read"], format="rfc3339" + ) + """Billing Period Start Date as in the invoice.""" + billing_period_end_date: Optional[datetime.datetime] = rest_field( + name="billingPeriodEndDate", visibility=["read"], format="rfc3339" + ) + """Billing Period End Date as in the invoice.""" + billing_profile_id: Optional[str] = rest_field(name="billingProfileId", visibility=["read"]) + """Identifier for the billing profile that groups costs across invoices in the a singular billing + currency across across the customers who have onboarded the Microsoft customer agreement and + the customers in CSP who have made entitlement purchases like SaaS, Marketplace, RI, etc.""" + billing_profile_name: Optional[str] = rest_field(name="billingProfileName", visibility=["read"]) + """Name of the billing profile that groups costs across invoices in the a singular billing + currency across across the customers who have onboarded the Microsoft customer agreement and + the customers in CSP who have made entitlement purchases like SaaS, Marketplace, RI, etc.""" + subscription_guid: Optional[str] = rest_field(name="subscriptionGuid", visibility=["read"]) + """Unique Microsoft generated identifier for the Azure Subscription.""" + subscription_name: Optional[str] = rest_field(name="subscriptionName", visibility=["read"]) + """Name of the Azure Subscription.""" + date: Optional[datetime.datetime] = rest_field(visibility=["read"], format="rfc3339") + """Date for the usage record.""" + product: Optional[str] = rest_field(visibility=["read"]) + """Name of the product that has accrued charges by consumption or purchase as listed in the + invoice. Not available for Marketplace.""" + meter_id: Optional[str] = rest_field(name="meterId", visibility=["read"]) + """The meter id (GUID). Not available for marketplace. For reserved instance this represents the + primary meter for which the reservation was purchased. For the actual VM Size for which the + reservation is purchased see productOrderName.""" + meter_name: Optional[str] = rest_field(name="meterName", visibility=["read"]) + """Identifies the name of the meter against which consumption is measured.""" + meter_region: Optional[str] = rest_field(name="meterRegion", visibility=["read"]) + """Identifies the location of the datacenter for certain services that are priced based on + datacenter location.""" + meter_category: Optional[str] = rest_field(name="meterCategory", visibility=["read"]) + """Identifies the top-level service for the usage.""" + meter_sub_category: Optional[str] = rest_field(name="meterSubCategory", visibility=["read"]) + """Defines the type or sub-category of Azure service that can affect the rate.""" + service_family: Optional[str] = rest_field(name="serviceFamily", visibility=["read"]) + """List the service family for the product purchased or charged (Example: Storage ; Compute).""" + quantity: Optional[decimal.Decimal] = rest_field(visibility=["read"]) + """Measure the quantity purchased or consumed.The amount of the meter used during the billing + period.""" + unit_of_measure: Optional[str] = rest_field(name="unitOfMeasure", visibility=["read"]) + """Identifies the Unit that the service is charged in. For example, GB, hours, 10,000 s.""" + instance_name: Optional[str] = rest_field(name="instanceName", visibility=["read"]) + """Instance Name.""" + cost_in_usd: Optional[decimal.Decimal] = rest_field(name="costInUSD", visibility=["read"]) + """Estimated extendedCost or blended cost before tax in USD.""" + unit_price: Optional[decimal.Decimal] = rest_field(name="unitPrice", visibility=["read"]) + """Unit Price is the price applicable to you. (your EA or other contract price).""" + billing_currency_code: Optional[str] = rest_field(name="billingCurrencyCode", visibility=["read"]) + """The currency defining the billed cost.""" + resource_location: Optional[str] = rest_field(name="resourceLocation", visibility=["read"]) + """Name of the resource location.""" + consumed_service: Optional[str] = rest_field(name="consumedService", visibility=["read"]) + """Consumed service name. Name of the azure resource provider that emits the usage or was + purchased. This value is not provided for marketplace usage.""" + service_info1: Optional[str] = rest_field(name="serviceInfo1", visibility=["read"]) + """Service-specific metadata.""" + service_info2: Optional[str] = rest_field(name="serviceInfo2", visibility=["read"]) + """Legacy field with optional service-specific metadata.""" + additional_info: Optional[str] = rest_field(name="additionalInfo", visibility=["read"]) + """Additional details of this usage item. Use this field to get usage line item specific details + such as the actual VM Size (ServiceType) or the ratio in which the reservation discount is + applied.""" + invoice_section_id: Optional[str] = rest_field(name="invoiceSectionId", visibility=["read"]) + """Identifier of the project that is being charged in the invoice. Not applicable for Microsoft + Customer Agreements onboarded by partners.""" + invoice_section_name: Optional[str] = rest_field(name="invoiceSectionName", visibility=["read"]) + """Name of the project that is being charged in the invoice. Not applicable for Microsoft Customer + Agreements onboarded by partners.""" + cost_center: Optional[str] = rest_field(name="costCenter", visibility=["read"]) + """The cost center of this department if it is a department and a cost center is provided.""" + resource_group: Optional[str] = rest_field(name="resourceGroup", visibility=["read"]) + """Name of the Azure resource group used for cohesive lifecycle management of resources.""" + reservation_id: Optional[str] = rest_field(name="reservationId", visibility=["read"]) + """ARM resource id of the reservation. Only applies to records relevant to reservations.""" + reservation_name: Optional[str] = rest_field(name="reservationName", visibility=["read"]) + """User provided display name of the reservation. Last known name for a particular day is + populated in the daily data. Only applies to records relevant to reservations.""" + product_order_id: Optional[str] = rest_field(name="productOrderId", visibility=["read"]) + """The identifier for the asset or Azure plan name that the subscription belongs to. For example: + Azure Plan. For reservations this is the Reservation Order ID.""" + product_order_name: Optional[str] = rest_field(name="productOrderName", visibility=["read"]) + """Product Order Name. For reservations this is the SKU that was purchased.""" + is_azure_credit_eligible: Optional[bool] = rest_field(name="isAzureCreditEligible", visibility=["read"]) + """Determines if the cost is eligible to be paid for using Azure credits.""" + term: Optional[str] = rest_field(visibility=["read"]) + """Term (in months). Displays the term for the validity of the offer. For example. In case of + reserved instances it displays 12 months for yearly term of reserved instance. For one time + purchases or recurring purchases, the terms displays 1 month; This is not applicable for Azure + consumption.""" + publisher_name: Optional[str] = rest_field(name="publisherName", visibility=["read"]) + """Name of the publisher of the service including Microsoft or Third Party publishers.""" + publisher_type: Optional[str] = rest_field(name="publisherType", visibility=["read"]) + """Type of publisher that identifies if the publisher is first party, third party reseller or + third party agency.""" + charge_type: Optional[str] = rest_field(name="chargeType", visibility=["read"]) + """Indicates a charge represents credits, usage, a Marketplace purchase, a reservation fee, or a + refund.""" + frequency: Optional[str] = rest_field(visibility=["read"]) + """Indicates how frequently this charge will occur. OneTime for purchases which only happen once, + Monthly for fees which recur every month, and UsageBased for charges based on how much a + service is used.""" + cost_in_billing_currency: Optional[decimal.Decimal] = rest_field(name="costInBillingCurrency", visibility=["read"]) + """ExtendedCost or blended cost before tax in billed currency.""" + cost_in_pricing_currency: Optional[decimal.Decimal] = rest_field(name="costInPricingCurrency", visibility=["read"]) + """ExtendedCost or blended cost before tax in pricing currency to correlate with prices.""" + exchange_rate: Optional[str] = rest_field(name="exchangeRate", visibility=["read"]) + """Exchange rate used in conversion from pricing currency to billing currency.""" + exchange_rate_date: Optional[datetime.datetime] = rest_field( + name="exchangeRateDate", visibility=["read"], format="rfc3339" + ) + """Date on which exchange rate used in conversion from pricing currency to billing currency.""" + invoice_id: Optional[str] = rest_field(name="invoiceId", visibility=["read"]) + """Invoice ID as on the invoice where the specific transaction appears.""" + previous_invoice_id: Optional[str] = rest_field(name="previousInvoiceId", visibility=["read"]) + """Reference to an original invoice there is a refund (negative cost). This is populated only when + there is a refund.""" + pricing_currency_code: Optional[str] = rest_field(name="pricingCurrencyCode", visibility=["read"]) + """Pricing Billing Currency.""" + product_identifier: Optional[str] = rest_field(name="productIdentifier", visibility=["read"]) + """Identifier for the product that has accrued charges by consumption or purchase . This is the + concatenated key of productId and SkuId in partner center.""" + resource_location_normalized: Optional[str] = rest_field(name="resourceLocationNormalized", visibility=["read"]) + """Resource Location Normalized.""" + service_period_start_date: Optional[datetime.datetime] = rest_field( + name="servicePeriodStartDate", visibility=["read"], format="rfc3339" + ) + """Start date for the rating period when the service usage was rated for charges. The prices for + Azure services are determined for the rating period.""" + service_period_end_date: Optional[datetime.datetime] = rest_field( + name="servicePeriodEndDate", visibility=["read"], format="rfc3339" + ) + """End date for the period when the service usage was rated for charges. The prices for Azure + services are determined based on the rating period.""" + customer_tenant_id: Optional[str] = rest_field(name="customerTenantId", visibility=["read"]) + """Identifier of the customer's AAD tenant.""" + customer_name: Optional[str] = rest_field(name="customerName", visibility=["read"]) + """Name of the customer's AAD tenant.""" + partner_tenant_id: Optional[str] = rest_field(name="partnerTenantId", visibility=["read"]) + """Identifier for the partner's AAD tenant.""" + partner_name: Optional[str] = rest_field(name="partnerName", visibility=["read"]) + """Name of the partner' AAD tenant.""" + reseller_mpn_id: Optional[str] = rest_field(name="resellerMpnId", visibility=["read"]) + """MPNId for the reseller associated with the subscription.""" + reseller_name: Optional[str] = rest_field(name="resellerName", visibility=["read"]) + """Reseller Name.""" + publisher_id: Optional[str] = rest_field(name="publisherId", visibility=["read"]) + """Publisher Id.""" + market_price: Optional[decimal.Decimal] = rest_field(name="marketPrice", visibility=["read"]) + """Market Price that's charged for the usage.""" + exchange_rate_pricing_to_billing: Optional[decimal.Decimal] = rest_field( + name="exchangeRatePricingToBilling", visibility=["read"] + ) + """Exchange Rate from pricing currency to billing currency.""" + payg_cost_in_billing_currency: Optional[decimal.Decimal] = rest_field( + name="paygCostInBillingCurrency", visibility=["read"] + ) + """The amount of PayG cost before tax in billing currency.""" + payg_cost_in_usd: Optional[decimal.Decimal] = rest_field(name="paygCostInUSD", visibility=["read"]) + """The amount of PayG cost before tax in US Dollar currency.""" + partner_earned_credit_rate: Optional[decimal.Decimal] = rest_field( + name="partnerEarnedCreditRate", visibility=["read"] + ) + """Rate of discount applied if there is a partner earned credit (PEC) based on partner admin link + access.""" + partner_earned_credit_applied: Optional[str] = rest_field(name="partnerEarnedCreditApplied", visibility=["read"]) + """Flag to indicate if partner earned credit has been applied or not.""" + pay_g_price: Optional[decimal.Decimal] = rest_field(name="payGPrice", visibility=["read"]) + """Retail price for the resource.""" + benefit_id: Optional[str] = rest_field(name="benefitId", visibility=["read"]) + """Unique identifier for the applicable benefit.""" + benefit_name: Optional[str] = rest_field(name="benefitName", visibility=["read"]) + """Name of the applicable benefit.""" + provider: Optional[str] = rest_field(visibility=["read"]) + """Identifier for Product Category or Line Of Business, Ex - Azure, Microsoft 365, AWS e.t.c.""" + cost_allocation_rule_name: Optional[str] = rest_field(name="costAllocationRuleName", visibility=["read"]) + """Name for Cost Allocation Rule.""" + + +class Notification(_Model): + """The notification associated with a budget. + + :ivar enabled: The notification is enabled or not. Required. + :vartype enabled: bool + :ivar operator: The comparison operator. Required. Known values are: "EqualTo", "GreaterThan", + and "GreaterThanOrEqualTo". + :vartype operator: str or ~azure.mgmt.consumption.models.OperatorType + :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: ~decimal.Decimal + :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. + :vartype contact_roles: list[str] + :ivar contact_groups: Action groups to send the budget notification to when the threshold is + 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" 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", and + "sv-se". + :vartype locale: str or ~azure.mgmt.consumption.models.CultureCode + """ + + enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The notification is enabled or not. Required.""" + operator: Union[str, "_models.OperatorType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The comparison operator. Required. Known values are: \"EqualTo\", \"GreaterThan\", and + \"GreaterThanOrEqualTo\".""" + threshold: decimal.Decimal = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """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.""" + contact_emails: list[str] = rest_field( + name="contactEmails", visibility=["read", "create", "update", "delete", "query"] + ) + """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.""" + contact_roles: Optional[list[str]] = rest_field( + name="contactRoles", visibility=["read", "create", "update", "delete", "query"] + ) + """Contact roles to send the budget notification to when the threshold is exceeded.""" + contact_groups: Optional[list[str]] = rest_field( + name="contactGroups", visibility=["read", "create", "update", "delete", "query"] + ) + """Action groups to send the budget notification to when the threshold is exceeded. Must be + provided as a fully qualified Azure resource id. Only supported at Subscription or Resource + Group scopes.""" + threshold_type: Optional[Union[str, "_models.ThresholdType"]] = rest_field( + name="thresholdType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of threshold. Known values are: \"Actual\" and \"Forecasted\".""" + locale: Optional[Union[str, "_models.CultureCode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """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\", and \"sv-se\".""" + + @overload + def __init__( + self, + *, + enabled: bool, + operator: Union[str, "_models.OperatorType"], + threshold: decimal.Decimal, + contact_emails: list[str], + contact_roles: Optional[list[str]] = None, + contact_groups: Optional[list[str]] = None, + threshold_type: Optional[Union[str, "_models.ThresholdType"]] = None, + locale: Optional[Union[str, "_models.CultureCode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Operation(_Model): + """A Consumption REST API operation. + + :ivar id: Operation Id. + :vartype id: str + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.consumption.models.OperationDisplay + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Operation Id.""" + name: Optional[str] = rest_field(visibility=["read"]) + """Operation name: {provider}/{resource}/{operation}.""" + display: Optional["_models.OperationDisplay"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The object that represents the operation.""" + + @overload + def __init__( + self, + *, + display: Optional["_models.OperationDisplay"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class OperationDisplay(_Model): + """The object that represents the operation. + + :ivar provider: Service provider: Microsoft.Consumption. + :vartype provider: str + :ivar resource: Resource on which the operation is performed: UsageDetail, etc. + :vartype resource: str + :ivar operation: Operation type: Read, write, delete, etc. + :vartype operation: str + :ivar description: Description of the operation. + :vartype description: str + """ + + provider: Optional[str] = rest_field(visibility=["read"]) + """Service provider: Microsoft.Consumption.""" + resource: Optional[str] = rest_field(visibility=["read"]) + """Resource on which the operation is performed: UsageDetail, etc.""" + operation: Optional[str] = rest_field(visibility=["read"]) + """Operation type: Read, write, delete, etc.""" + description: Optional[str] = rest_field(visibility=["read"]) + """Description of the operation.""" + + +class OperationStatus(_Model): + """The status of the long running operation. + + :ivar status: The status of the long running operation. Known values are: "Running", + "Completed", and "Failed". + :vartype status: str or ~azure.mgmt.consumption.models.OperationStatusType + :ivar properties: The properties of the resource generated. + :vartype properties: ~azure.mgmt.consumption.models.PricesheetDownloadProperties + """ + + status: Optional[Union[str, "_models.OperationStatusType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The status of the long running operation. Known values are: \"Running\", \"Completed\", and + \"Failed\".""" + properties: Optional["_models.PricesheetDownloadProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the resource generated.""" + + __flattened_items = ["download_url", "valid_till"] + + @overload + def __init__( + self, + *, + status: Optional[Union[str, "_models.OperationStatusType"]] = None, + properties: Optional["_models.PricesheetDownloadProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class PricesheetDownloadProperties(_Model): + """The properties of the price sheet download. + + :ivar download_url: The link (url) to download the pricesheet. + :vartype download_url: str + :ivar valid_till: Download link validity. + :vartype valid_till: ~datetime.datetime + """ + + download_url: Optional[str] = rest_field(name="downloadUrl", visibility=["read"]) + """The link (url) to download the pricesheet.""" + valid_till: Optional[datetime.datetime] = rest_field(name="validTill", visibility=["read"], format="rfc3339") + """Download link validity.""" + + +class PriceSheetModel(_Model): + """price sheet result. It contains the pricesheet associated with billing period. + + :ivar pricesheets: Price sheet. + :vartype pricesheets: list[~azure.mgmt.consumption.models.PriceSheetProperties] + :ivar next_link: The link (url) to the next page of results. + :vartype next_link: str + :ivar download: Pricesheet download details. + :vartype download: ~azure.mgmt.consumption.models.MeterDetails + """ + + pricesheets: Optional[list["_models.PriceSheetProperties"]] = rest_field(visibility=["read"]) + """Price sheet.""" + next_link: Optional[str] = rest_field(name="nextLink", visibility=["read"]) + """The link (url) to the next page of results.""" + download: Optional["_models.MeterDetails"] = rest_field(visibility=["read"]) + """Pricesheet download details.""" + + +class PriceSheetProperties(_Model): + """The properties of the price sheet. + + :ivar billing_period_id: The id of the billing period resource that the usage belongs to. + :vartype billing_period_id: str + :ivar meter_id: The meter id (GUID). + :vartype meter_id: str + :ivar meter_details: The details about the meter. By default this is not populated, unless it's + specified in $expand. + :vartype meter_details: ~azure.mgmt.consumption.models.MeterDetails + :ivar unit_of_measure: Unit of measure. + :vartype unit_of_measure: str + :ivar included_quantity: Included quality for an offer. + :vartype included_quantity: ~decimal.Decimal + :ivar part_number: Part Number. + :vartype part_number: str + :ivar unit_price: Unit Price. + :vartype unit_price: ~decimal.Decimal + :ivar currency_code: Currency Code. + :vartype currency_code: str + :ivar offer_id: Offer Id. + :vartype offer_id: str + :ivar savings_plan: SavingsPlan Details. + :vartype savings_plan: ~azure.mgmt.consumption.models.SavingsPlan + """ + + billing_period_id: Optional[str] = rest_field(name="billingPeriodId", visibility=["read"]) + """The id of the billing period resource that the usage belongs to.""" + meter_id: Optional[str] = rest_field(name="meterId", visibility=["read"]) + """The meter id (GUID).""" + meter_details: Optional["_models.MeterDetails"] = rest_field(name="meterDetails", visibility=["read"]) + """The details about the meter. By default this is not populated, unless it's specified in + $expand.""" + unit_of_measure: Optional[str] = rest_field(name="unitOfMeasure", visibility=["read"]) + """Unit of measure.""" + included_quantity: Optional[decimal.Decimal] = rest_field(name="includedQuantity", visibility=["read"]) + """Included quality for an offer.""" + part_number: Optional[str] = rest_field(name="partNumber", visibility=["read"]) + """Part Number.""" + unit_price: Optional[decimal.Decimal] = rest_field(name="unitPrice", visibility=["read"]) + """Unit Price.""" + currency_code: Optional[str] = rest_field(name="currencyCode", visibility=["read"]) + """Currency Code.""" + offer_id: Optional[str] = rest_field(name="offerId", visibility=["read"]) + """Offer Id.""" + savings_plan: Optional["_models.SavingsPlan"] = rest_field(name="savingsPlan", visibility=["read"]) + """SavingsPlan Details.""" + + +class PriceSheetResult(ProxyResource): + """An pricesheet resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: price sheet result. It contains the pricesheet associated with billing + period. + :vartype properties: ~azure.mgmt.consumption.models.PriceSheetModel + :ivar etag: 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 etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + properties: Optional["_models.PriceSheetModel"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """price sheet result. It contains the pricesheet associated with billing period.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """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.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = ["pricesheets", "next_link", "download"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.PriceSheetModel"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class Reseller(_Model): + """The reseller properties. + + :ivar reseller_id: The reseller property ID. + :vartype reseller_id: str + :ivar reseller_description: The reseller property description. + :vartype reseller_description: str + """ + + reseller_id: Optional[str] = rest_field(name="resellerId", visibility=["read"]) + """The reseller property ID.""" + reseller_description: Optional[str] = rest_field(name="resellerDescription", visibility=["read"]) + """The reseller property description.""" + + +class ReservationDetail(Resource): + """reservation detail resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the reservation detail. + :vartype properties: ~azure.mgmt.consumption.models.ReservationDetailProperties + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + properties: Optional["_models.ReservationDetailProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the reservation detail.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = [ + "reservation_order_id", + "instance_flexibility_ratio", + "instance_flexibility_group", + "reservation_id", + "sku_name", + "reserved_hours", + "usage_date", + "used_hours", + "instance_id", + "total_reserved_quantity", + "kind", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.ReservationDetailProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ReservationDetailProperties(_Model): + """The properties of the reservation detail. + + :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 + order contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype reservation_order_id: str + :ivar instance_flexibility_ratio: The instance Flexibility Ratio. + :vartype instance_flexibility_ratio: str + :ivar instance_flexibility_group: The instance Flexibility Group. + :vartype instance_flexibility_group: str + :ivar reservation_id: The reservation ID is the identifier of a reservation within a + reservation order. Each reservation is the grouping for applying the benefit scope and also + specifies the number of instances to which the reservation benefit can be applied to. + :vartype reservation_id: str + :ivar sku_name: This is the ARM Sku name. It can be used to join with the serviceType field in + additional info in usage records. + :vartype sku_name: str + :ivar reserved_hours: This is the total hours reserved for the day. E.g. if reservation for 1 + instance was made on 1 PM, this will be 11 hours for that day and 24 hours from subsequent + days. + :vartype reserved_hours: ~decimal.Decimal + :ivar usage_date: The date on which consumption occurred. + :vartype usage_date: ~datetime.datetime + :ivar used_hours: This is the total hours used by the instance. + :vartype used_hours: ~decimal.Decimal + :ivar instance_id: This identifier is the name of the resource or the fully qualified Resource + ID. + :vartype instance_id: str + :ivar total_reserved_quantity: This is the total count of instances that are reserved for the + reservationId. + :vartype total_reserved_quantity: ~decimal.Decimal + :ivar kind: The reservation kind. + :vartype kind: str + """ + + reservation_order_id: Optional[str] = rest_field(name="reservationOrderId", visibility=["read"]) + """The reservation order ID is the identifier for a reservation purchase. Each reservation order + ID represents a single purchase transaction. A reservation order contains reservations. The + reservation order specifies the VM size and region for the reservations.""" + instance_flexibility_ratio: Optional[str] = rest_field(name="instanceFlexibilityRatio", visibility=["read"]) + """The instance Flexibility Ratio.""" + instance_flexibility_group: Optional[str] = rest_field(name="instanceFlexibilityGroup", visibility=["read"]) + """The instance Flexibility Group.""" + reservation_id: Optional[str] = rest_field(name="reservationId", visibility=["read"]) + """The reservation ID is the identifier of a reservation within a reservation order. Each + reservation is the grouping for applying the benefit scope and also specifies the number of + instances to which the reservation benefit can be applied to.""" + sku_name: Optional[str] = rest_field(name="skuName", visibility=["read"]) + """This is the ARM Sku name. It can be used to join with the serviceType field in additional info + in usage records.""" + reserved_hours: Optional[decimal.Decimal] = rest_field(name="reservedHours", visibility=["read"]) + """This is the total hours reserved for the day. E.g. if reservation for 1 instance was made on 1 + PM, this will be 11 hours for that day and 24 hours from subsequent days.""" + usage_date: Optional[datetime.datetime] = rest_field(name="usageDate", visibility=["read"], format="rfc3339") + """The date on which consumption occurred.""" + used_hours: Optional[decimal.Decimal] = rest_field(name="usedHours", visibility=["read"]) + """This is the total hours used by the instance.""" + instance_id: Optional[str] = rest_field(name="instanceId", visibility=["read"]) + """This identifier is the name of the resource or the fully qualified Resource ID.""" + total_reserved_quantity: Optional[decimal.Decimal] = rest_field(name="totalReservedQuantity", visibility=["read"]) + """This is the total count of instances that are reserved for the reservationId.""" + kind: Optional[str] = rest_field(visibility=["read"]) + """The reservation kind.""" + + +class ReservationRecommendationDetailsCalculatedSavingsProperties(_Model): # pylint: disable=name-too-long + """Details of estimated savings. The costs and savings are estimated for the term. + + :ivar on_demand_cost: The cost without reservation. Includes hardware and software cost. + :vartype on_demand_cost: float + :ivar overage_cost: The estimated cost for resource meters that are not covered by the + reservation and are billed at pay-as-you-go rates. + :vartype overage_cost: float + :ivar quantity: The quantity for calculated savings. + :vartype quantity: float + :ivar reservation_cost: Hardware cost of the resources covered by the reservation. + :vartype reservation_cost: float + :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. This is + equal to onDemandCost - totalReservationCost. + :vartype savings: float + """ + + on_demand_cost: Optional[float] = rest_field(name="onDemandCost", visibility=["read"]) + """The cost without reservation. Includes hardware and software cost.""" + overage_cost: Optional[float] = rest_field(name="overageCost", visibility=["read"]) + """The estimated cost for resource meters that are not covered by the reservation and are billed + at pay-as-you-go rates.""" + quantity: Optional[float] = rest_field(visibility=["read"]) + """The quantity for calculated savings.""" + reservation_cost: Optional[float] = rest_field(name="reservationCost", visibility=["read"]) + """Hardware cost of the resources covered by the reservation.""" + total_reservation_cost: Optional[float] = rest_field(name="totalReservationCost", visibility=["read"]) + """Reservation cost + software cost of the resources covered by the reservation + overage cost.""" + reserved_unit_count: Optional[float] = rest_field( + name="reservedUnitCount", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of reserved units used to calculate savings. Always 1 for virtual machines.""" + savings: Optional[float] = rest_field(visibility=["read"]) + """The amount saved by purchasing the recommended quantity of reservation. This is equal to + onDemandCost - totalReservationCost.""" + + @overload + def __init__( + self, + *, + reserved_unit_count: Optional[float] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ReservationRecommendationDetailsModel(Resource): + """Reservation recommendation details. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar location: Resource Location. + :vartype location: str + :ivar sku: Resource sku. + :vartype sku: str + :ivar properties: The properties of the reservation recommendation. + :vartype properties: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsProperties + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + location: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource Location.""" + sku: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource sku.""" + properties: Optional["_models.ReservationRecommendationDetailsProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the reservation recommendation.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = ["currency", "resource", "resource_group", "savings", "scope", "usage"] + + @overload + def __init__( + self, + *, + location: Optional[str] = None, + sku: Optional[str] = None, + properties: Optional["_models.ReservationRecommendationDetailsProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ReservationRecommendationDetailsProperties(_Model): # pylint: disable=name-too-long + """The properties of the reservation recommendation. + + :ivar currency: An ISO 4217 currency code identifier for the costs and savings. + :vartype currency: str + :ivar resource: Resource specific properties. + :vartype resource: + ~azure.mgmt.consumption.models.ReservationRecommendationDetailsResourceProperties + :ivar resource_group: Resource Group. + :vartype resource_group: str + :ivar savings: Savings information for the recommendation. + :vartype savings: + ~azure.mgmt.consumption.models.ReservationRecommendationDetailsSavingsProperties + :ivar scope: Scope of the reservation, ex: Single or Shared. + :vartype scope: str + :ivar usage: Historical usage details used to calculate the estimated savings. + :vartype usage: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsUsageProperties + """ + + currency: Optional[str] = rest_field(visibility=["read"]) + """An ISO 4217 currency code identifier for the costs and savings.""" + resource: Optional["_models.ReservationRecommendationDetailsResourceProperties"] = rest_field(visibility=["read"]) + """Resource specific properties.""" + resource_group: Optional[str] = rest_field(name="resourceGroup", visibility=["read"]) + """Resource Group.""" + savings: Optional["_models.ReservationRecommendationDetailsSavingsProperties"] = rest_field(visibility=["read"]) + """Savings information for the recommendation.""" + scope: Optional[str] = rest_field(visibility=["read"]) + """Scope of the reservation, ex: Single or Shared.""" + usage: Optional["_models.ReservationRecommendationDetailsUsageProperties"] = rest_field(visibility=["read"]) + """Historical usage details used to calculate the estimated savings.""" + + +class ReservationRecommendationDetailsResourceProperties(_Model): # pylint: disable=name-too-long + """Details of the resource. + + :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. Most resources use hourly rates, except + for BlockBlob, ManagedDisk, Backup, and Azure Files, which use monthly rates. Only hardware + rates are included; software rates are excluded. Note: there could be new resources that use + hourly rates in the future. + :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: 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 + """ + + applied_scopes: Optional[list[str]] = rest_field(name="appliedScopes", visibility=["read"]) + """List of subscriptions for which the reservation is applied.""" + on_demand_rate: Optional[float] = rest_field(name="onDemandRate", visibility=["read"]) + """On-demand rate of the resource. Most resources use hourly rates, except for BlockBlob, + ManagedDisk, Backup, and Azure Files, which use monthly rates. Only hardware rates are + included; software rates are excluded. Note: there could be new resources that use hourly + rates in the future.""" + product: Optional[str] = rest_field(visibility=["read"]) + """Azure product ex: Standard_E8s_v3 etc.""" + region: Optional[str] = rest_field(visibility=["read"]) + """Azure resource region ex:EastUS, WestUS etc.""" + reservation_rate: Optional[float] = rest_field(name="reservationRate", visibility=["read"]) + """Hourly reservation rate of the resource. Varies based on the term.""" + resource_type: Optional[str] = rest_field(name="resourceType", visibility=["read"]) + """The azure resource type.""" + + +class ReservationRecommendationDetailsSavingsProperties(_Model): # pylint: disable=name-too-long + """Details of the estimated savings. + + :ivar calculated_savings: List of calculated savings. + :vartype calculated_savings: + list[~azure.mgmt.consumption.models.ReservationRecommendationDetailsCalculatedSavingsProperties] + :ivar look_back_period: Number of days of usage to look back used for computing the + recommendation. + :vartype look_back_period: int + :ivar recommended_quantity: Number of recommended units of the resource. + :vartype recommended_quantity: float + :ivar reservation_order_term: Term period of the reservation. ex: P1M, P1Y or P3Y. + :vartype reservation_order_term: str + :ivar savings_type: Type of savings, ex: instance. + :vartype savings_type: str + :ivar unit_of_measure: Measurement unit ex: hour etc. + :vartype unit_of_measure: str + """ + + calculated_savings: Optional[list["_models.ReservationRecommendationDetailsCalculatedSavingsProperties"]] = ( + rest_field(name="calculatedSavings", visibility=["read", "create", "update", "delete", "query"]) + ) + """List of calculated savings.""" + look_back_period: Optional[int] = rest_field(name="lookBackPeriod", visibility=["read"]) + """Number of days of usage to look back used for computing the recommendation.""" + recommended_quantity: Optional[float] = rest_field(name="recommendedQuantity", visibility=["read"]) + """Number of recommended units of the resource.""" + reservation_order_term: Optional[str] = rest_field(name="reservationOrderTerm", visibility=["read"]) + """Term period of the reservation. ex: P1M, P1Y or P3Y.""" + savings_type: Optional[str] = rest_field(name="savingsType", visibility=["read"]) + """Type of savings, ex: instance.""" + unit_of_measure: Optional[str] = rest_field(name="unitOfMeasure", visibility=["read"]) + """Measurement unit ex: hour etc.""" + + @overload + def __init__( + self, + *, + calculated_savings: Optional[ + list["_models.ReservationRecommendationDetailsCalculatedSavingsProperties"] + ] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ReservationRecommendationDetailsUsageProperties(_Model): # pylint: disable=name-too-long + """Details about historical usage data that has been used for computing the recommendation. + + :ivar first_consumption_date: The first usage date used for looking back for computing the + recommendation. + :vartype first_consumption_date: str + :ivar last_consumption_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_consumption_date: str + :ivar look_back_unit_type: What the usage data values represent ex: virtual machine instance. + :vartype look_back_unit_type: str + :ivar usage_data: The breakdown of historical resource usage. The values are in the order of + usage between the firstConsumptionDate and the lastConsumptionDate. + :vartype usage_data: list[float] + :ivar usage_grain: The grain of the values represented in the usage data ex: hourly. + :vartype usage_grain: str + """ + + first_consumption_date: Optional[str] = rest_field(name="firstConsumptionDate", visibility=["read"]) + """The first usage date used for looking back for computing the recommendation.""" + last_consumption_date: Optional[str] = rest_field(name="lastConsumptionDate", visibility=["read"]) + """The last usage date used for looking back for computing the recommendation.""" + look_back_unit_type: Optional[str] = rest_field(name="lookBackUnitType", visibility=["read"]) + """What the usage data values represent ex: virtual machine instance.""" + usage_data: Optional[list[float]] = rest_field(name="usageData", visibility=["read"]) + """The breakdown of historical resource usage. The values are in the order of usage between the + firstConsumptionDate and the lastConsumptionDate.""" + usage_grain: Optional[str] = rest_field(name="usageGrain", visibility=["read"]) + """The grain of the values represented in the usage data ex: hourly.""" + + +class ReservationSummary(Resource): + """reservation summary resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the reservation summary. + :vartype properties: ~azure.mgmt.consumption.models.ReservationSummaryProperties + :ivar etag: The etag for the resource. + :vartype etag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + properties: Optional["_models.ReservationSummaryProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the reservation summary.""" + etag: Optional[str] = rest_field(visibility=["read"]) + """The etag for the resource.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = [ + "reservation_order_id", + "reservation_id", + "sku_name", + "reserved_hours", + "usage_date", + "used_hours", + "min_utilization_percentage", + "avg_utilization_percentage", + "max_utilization_percentage", + "kind", + "purchased_quantity", + "remaining_quantity", + "total_reserved_quantity", + "used_quantity", + "utilized_percentage", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.ReservationSummaryProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class ReservationSummaryProperties(_Model): + """The properties of the reservation summary. + + :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 + order contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype reservation_order_id: str + :ivar reservation_id: The reservation ID is the identifier of a reservation within a + reservation order. Each reservation is the grouping for applying the benefit scope and also + specifies the number of instances to which the reservation benefit can be applied to. + :vartype reservation_id: str + :ivar sku_name: This is the ARM Sku name. It can be used to join with the serviceType field in + additional info in usage records. + :vartype sku_name: str + :ivar reserved_hours: This is the total hours reserved. E.g. if reservation for 1 instance was + made on 1 PM, this will be 11 hours for that day and 24 hours from subsequent days. + :vartype reserved_hours: ~decimal.Decimal + :ivar usage_date: Data corresponding to the utilization record. If the grain of data is + monthly, it will be first day of month. + :vartype usage_date: ~datetime.datetime + :ivar used_hours: Total used hours by the reservation. + :vartype used_hours: ~decimal.Decimal + :ivar min_utilization_percentage: This is the minimum hourly utilization in the usage time (day + or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4 and 5, + utilization was 10%, this field will return 10% for that day. + :vartype min_utilization_percentage: ~decimal.Decimal + :ivar avg_utilization_percentage: This is average utilization for the entire time range. (day + or month depending on the grain). + :vartype avg_utilization_percentage: ~decimal.Decimal + :ivar max_utilization_percentage: This is the maximum hourly utilization in the usage time (day + or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4 and 5, + utilization was 100%, this field will return 100% for that day. + :vartype max_utilization_percentage: ~decimal.Decimal + :ivar kind: The reservation kind. + :vartype kind: str + :ivar purchased_quantity: This is the purchased quantity for the reservationId. + :vartype purchased_quantity: ~decimal.Decimal + :ivar remaining_quantity: This is the remaining quantity for the reservationId. + :vartype remaining_quantity: ~decimal.Decimal + :ivar total_reserved_quantity: This is the total count of instances that are reserved for the + reservationId. + :vartype total_reserved_quantity: ~decimal.Decimal + :ivar used_quantity: This is the used quantity for the reservationId. + :vartype used_quantity: ~decimal.Decimal + :ivar utilized_percentage: This is the utilized percentage for the reservation Id. + :vartype utilized_percentage: ~decimal.Decimal + """ + + reservation_order_id: Optional[str] = rest_field(name="reservationOrderId", visibility=["read"]) + """The reservation order ID is the identifier for a reservation purchase. Each reservation order + ID represents a single purchase transaction. A reservation order contains reservations. The + reservation order specifies the VM size and region for the reservations.""" + reservation_id: Optional[str] = rest_field(name="reservationId", visibility=["read"]) + """The reservation ID is the identifier of a reservation within a reservation order. Each + reservation is the grouping for applying the benefit scope and also specifies the number of + instances to which the reservation benefit can be applied to.""" + sku_name: Optional[str] = rest_field(name="skuName", visibility=["read"]) + """This is the ARM Sku name. It can be used to join with the serviceType field in additional info + in usage records.""" + reserved_hours: Optional[decimal.Decimal] = rest_field(name="reservedHours", visibility=["read"]) + """This is the total hours reserved. E.g. if reservation for 1 instance was made on 1 PM, this + will be 11 hours for that day and 24 hours from subsequent days.""" + usage_date: Optional[datetime.datetime] = rest_field(name="usageDate", visibility=["read"], format="rfc3339") + """Data corresponding to the utilization record. If the grain of data is monthly, it will be first + day of month.""" + used_hours: Optional[decimal.Decimal] = rest_field(name="usedHours", visibility=["read"]) + """Total used hours by the reservation.""" + min_utilization_percentage: Optional[decimal.Decimal] = rest_field( + name="minUtilizationPercentage", visibility=["read"] + ) + """This is the minimum hourly utilization in the usage time (day or month). E.g. if usage record + corresponds to 12/10/2017 and on that for hour 4 and 5, utilization was 10%, this field will + return 10% for that day.""" + avg_utilization_percentage: Optional[decimal.Decimal] = rest_field( + name="avgUtilizationPercentage", visibility=["read"] + ) + """This is average utilization for the entire time range. (day or month depending on the grain).""" + max_utilization_percentage: Optional[decimal.Decimal] = rest_field( + name="maxUtilizationPercentage", visibility=["read"] + ) + """This is the maximum hourly utilization in the usage time (day or month). E.g. if usage record + corresponds to 12/10/2017 and on that for hour 4 and 5, utilization was 100%, this field will + return 100% for that day.""" + kind: Optional[str] = rest_field(visibility=["read"]) + """The reservation kind.""" + purchased_quantity: Optional[decimal.Decimal] = rest_field(name="purchasedQuantity", visibility=["read"]) + """This is the purchased quantity for the reservationId.""" + remaining_quantity: Optional[decimal.Decimal] = rest_field(name="remainingQuantity", visibility=["read"]) + """This is the remaining quantity for the reservationId.""" + total_reserved_quantity: Optional[decimal.Decimal] = rest_field(name="totalReservedQuantity", visibility=["read"]) + """This is the total count of instances that are reserved for the reservationId.""" + used_quantity: Optional[decimal.Decimal] = rest_field(name="usedQuantity", visibility=["read"]) + """This is the used quantity for the reservationId.""" + utilized_percentage: Optional[decimal.Decimal] = rest_field(name="utilizedPercentage", visibility=["read"]) + """This is the utilized percentage for the reservation Id.""" + + +class ReservationTransaction(Resource): + """Reservation transaction resource. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of a legacy reservation transaction. + :vartype properties: ~azure.mgmt.consumption.models.LegacyReservationTransactionProperties + :ivar tags: Resource tags. + :vartype tags: list[str] + """ + + properties: Optional["_models.LegacyReservationTransactionProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of a legacy reservation transaction.""" + tags: Optional[list[str]] = rest_field(visibility=["read"]) + """Resource tags.""" + + __flattened_items = [ + "event_date", + "reservation_order_id", + "description", + "event_type", + "quantity", + "amount", + "currency", + "reservation_order_name", + "purchasing_enrollment", + "purchasing_subscription_guid", + "purchasing_subscription_name", + "arm_sku_name", + "term", + "region", + "account_name", + "account_owner_email", + "department_name", + "cost_center", + "current_enrollment", + "billing_frequency", + "billing_month", + "monetary_commitment", + "overage", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.LegacyReservationTransactionProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) + + +class SavingsPlan(_Model): + """The properties of the SavingsPlan. + + :ivar term: SavingsPlan term. + :vartype term: str + :ivar market_price: SavingsPlan Market Price. + :vartype market_price: ~decimal.Decimal + :ivar effective_price: SavingsPlan Effective Price. + :vartype effective_price: ~decimal.Decimal + """ + + term: Optional[str] = rest_field(visibility=["read"]) + """SavingsPlan term.""" + market_price: Optional[decimal.Decimal] = rest_field(name="marketPrice", visibility=["read"]) + """SavingsPlan Market Price.""" + effective_price: Optional[decimal.Decimal] = rest_field(name="effectivePrice", visibility=["read"]) + """SavingsPlan Effective Price.""" + + +class SkuProperty(_Model): + """The Sku property. + + :ivar name: The name of sku property. + :vartype name: str + :ivar value: The value of sku property. + :vartype value: str + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """The name of sku property.""" + value: Optional[str] = rest_field(visibility=["read"]) + """The value of sku property.""" + + +class SystemData(_Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.consumption.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.consumption.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read", "create", "update", "delete", "query"]) + """The identity that created the resource.""" + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="createdByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that created the resource. Known values are: \"User\", \"Application\", + \"ManagedIdentity\", and \"Key\".""" + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource creation (UTC).""" + last_modified_by: Optional[str] = rest_field( + name="lastModifiedBy", visibility=["read", "create", "update", "delete", "query"] + ) + """The identity that last modified the resource.""" + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="lastModifiedByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that last modified the resource. Known values are: \"User\", + \"Application\", \"ManagedIdentity\", and \"Key\".""" + last_modified_at: Optional[datetime.datetime] = rest_field( + name="lastModifiedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource last modification (UTC).""" + + @overload + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Tag(_Model): + """The tag resource. + + :ivar key: Tag key. + :vartype key: str + :ivar value: Tag values. + :vartype value: list[str] + """ + + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tag key.""" + value: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tag values.""" + + @overload + def __init__( + self, + *, + key: Optional[str] = None, + value: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TagProperties(_Model): + """The properties of the 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 + :ivar previous_link: The link (url) to the previous page of results. + :vartype previous_link: str + """ + + tags: Optional[list["_models.Tag"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of Tag.""" + next_link: Optional[str] = rest_field(name="nextLink", visibility=["read"]) + """The link (url) to the next page of results.""" + previous_link: Optional[str] = rest_field(name="previousLink", visibility=["read"]) + """The link (url) to the previous page of results.""" + + @overload + def __init__( + self, + *, + tags: Optional[list["_models.Tag"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TagsResult(ProxyResource): + """A resource listing all tags. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.consumption.models.SystemData + :ivar properties: The properties of the tag. + :vartype properties: ~azure.mgmt.consumption.models.TagProperties + :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 + """ + + properties: Optional["_models.TagProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties of the tag.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """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.""" + + __flattened_items = ["tags", "next_link", "previous_link"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.TagProperties"] = None, + e_tag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + _flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items} + super().__init__(*args, **kwargs) + for k, v in _flattened_input.items(): + setattr(self, k, v) + + def __getattr__(self, name: str) -> Any: + if name in self.__flattened_items: + if self.properties is None: + return None + return getattr(self.properties, name) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") + + def __setattr__(self, key: str, value: Any) -> None: + if key in self.__flattened_items: + if self.properties is None: + self.properties = self._attr_to_rest_field["properties"]._class_type() + setattr(self.properties, key, value) + else: + super().__setattr__(key, value) 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 deleted file mode 100644 index a3d280e095a9..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/models/_models_py3.py +++ /dev/null @@ -1,5341 +0,0 @@ -# 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. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Dict, List, Optional, TYPE_CHECKING, Union - -from .. import _serialization - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from .. import models as _models - - -class Amount(_serialization.Model): - """The amount plus currency . - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar currency: Amount currency. - :vartype currency: str - :ivar value: Amount. - :vartype value: float - """ - - _validation = { - "currency": {"readonly": True}, - "value": {"readonly": True}, - } - - _attribute_map = { - "currency": {"key": "currency", "type": "str"}, - "value": {"key": "value", "type": "float"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.currency = None - self.value = None - - -class AmountWithExchangeRate(Amount): - """The amount with exchange rate. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar currency: Amount currency. - :vartype currency: str - :ivar value: Amount. - :vartype value: float - :ivar exchange_rate: The exchange rate. - :vartype exchange_rate: float - :ivar exchange_rate_month: The exchange rate month. - :vartype exchange_rate_month: int - """ - - _validation = { - "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"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.exchange_rate = None - self.exchange_rate_month = None - - -class Resource(_serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :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}, - } - - _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}"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.etag = None - self.tags = None - - -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. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :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 - :ivar beginning_balance: The beginning balance for the billing period. - :vartype beginning_balance: float - :ivar ending_balance: The ending balance for the billing period (for open periods this will be - updated daily). - :vartype ending_balance: float - :ivar new_purchases: Total new purchase amount. - :vartype new_purchases: float - :ivar adjustments: Total adjustment amount. - :vartype adjustments: float - :ivar utilized: Total Commitment usage. - :vartype utilized: float - :ivar service_overage: Overage for Azure services. - :vartype service_overage: float - :ivar charges_billed_separately: Charges Billed separately. - :vartype charges_billed_separately: float - :ivar total_overage: serviceOverage + chargesBilledSeparately. - :vartype total_overage: float - :ivar total_usage: Azure service commitment + total Overage. - :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", and - "Year". - :vartype billing_frequency: str or ~azure.mgmt.consumption.models.BillingFrequency - :ivar price_hidden: Price is hidden or not. - :vartype price_hidden: bool - :ivar new_purchases_details: List of new purchases. - :vartype new_purchases_details: - list[~azure.mgmt.consumption.models.BalancePropertiesNewPurchasesDetailsItem] - :ivar adjustment_details: List of Adjustments (Promo credit, SIE credit etc.). - :vartype adjustment_details: - list[~azure.mgmt.consumption.models.BalancePropertiesAdjustmentDetailsItem] - """ - - _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}, - } - - _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", and - "Year". - :paramtype billing_frequency: str or ~azure.mgmt.consumption.models.BillingFrequency - """ - super().__init__(**kwargs) - self.currency = None - self.beginning_balance = None - self.ending_balance = None - self.new_purchases = None - self.adjustments = None - self.utilized = None - self.service_overage = None - self.charges_billed_separately = None - self.total_overage = None - self.total_usage = None - self.azure_marketplace_service_charges = None - self.billing_frequency = billing_frequency - self.price_hidden = None - self.new_purchases_details = None - self.adjustment_details = None - - -class BalancePropertiesAdjustmentDetailsItem(_serialization.Model): - """BalancePropertiesAdjustmentDetailsItem. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: the name of new adjustment. - :vartype name: str - :ivar value: the value of new adjustment. - :vartype value: float - """ - - _validation = { - "name": {"readonly": True}, - "value": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "value": {"key": "value", "type": "float"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.name = None - self.value = None - - -class BalancePropertiesNewPurchasesDetailsItem(_serialization.Model): - """BalancePropertiesNewPurchasesDetailsItem. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: the name of new purchase. - :vartype name: str - :ivar value: the value of new purchase. - :vartype value: float - """ - - _validation = { - "name": {"readonly": True}, - "value": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "value": {"key": "value", "type": "float"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.name = None - self.value = None - - -class ProxyResource(_serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :vartype e_tag: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "e_tag": {"key": "eTag", "type": "str"}, - } - - def __init__(self, *, e_tag: Optional[str] = None, **kwargs): - """ - :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :paramtype e_tag: str - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.e_tag = e_tag - - -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. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :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 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", 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. - Future start date should not be more than twelve months. Past start date should be selected - within the timegrain period. There are no restrictions on the end date. - :vartype time_period: ~azure.mgmt.consumption.models.BudgetTimePeriod - :ivar filter: May be used to filter budgets by user-specified dimensions and/or tags. - :vartype filter: ~azure.mgmt.consumption.models.BudgetFilter - :ivar current_spend: The current amount of cost which is being tracked for a budget. - :vartype current_spend: ~azure.mgmt.consumption.models.CurrentSpend - :ivar notifications: Dictionary of notifications associated with the budget. Budget can have up - to five notifications. - :vartype notifications: dict[str, ~azure.mgmt.consumption.models.Notification] - :ivar forecast_spend: The forecasted cost which is being tracked for a budget. - :vartype forecast_spend: ~azure.mgmt.consumption.models.ForecastSpend - """ - - _validation = { - "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"}, - } - - def __init__( - self, - *, - e_tag: Optional[str] = None, - category: Optional[Union[str, "_models.CategoryType"]] = None, - amount: Optional[float] = None, - time_grain: Optional[Union[str, "_models.TimeGrainType"]] = None, - time_period: Optional["_models.BudgetTimePeriod"] = None, - filter: Optional["_models.BudgetFilter"] = None, # pylint: disable=redefined-builtin - notifications: Optional[Dict[str, "_models.Notification"]] = 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 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", 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. - Future start date should not be more than twelve months. Past start date should be selected - within the timegrain period. There are no restrictions on the end date. - :paramtype time_period: ~azure.mgmt.consumption.models.BudgetTimePeriod - :keyword filter: May be used to filter budgets by user-specified dimensions and/or tags. - :paramtype filter: ~azure.mgmt.consumption.models.BudgetFilter - :keyword notifications: Dictionary of notifications associated with the budget. Budget can have - up to five notifications. - :paramtype notifications: dict[str, ~azure.mgmt.consumption.models.Notification] - """ - super().__init__(e_tag=e_tag, **kwargs) - self.category = category - self.amount = amount - self.time_grain = time_grain - self.time_period = time_period - self.filter = filter - self.current_spend = None - self.notifications = notifications - self.forecast_spend = None - - -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: The name of the column to use in comparison. Required. - :vartype name: str - :ivar operator: The operator to use for comparison. Required. "In" - :vartype operator: str or ~azure.mgmt.consumption.models.BudgetOperatorType - :ivar values: Array of values to use for comparison. Required. - :vartype values: list[str] - """ - - _validation = { - "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]"}, - } - - def __init__(self, *, name: str, operator: Union[str, "_models.BudgetOperatorType"], values: List[str], **kwargs): - """ - :keyword name: The name of the column to use in comparison. Required. - :paramtype name: str - :keyword operator: The operator to use for comparison. Required. "In" - :paramtype operator: str or ~azure.mgmt.consumption.models.BudgetOperatorType - :keyword values: Array of values to use for comparison. Required. - :paramtype values: list[str] - """ - super().__init__(**kwargs) - self.name = name - self.operator = operator - self.values = values - - -class 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: 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"}, - } - - def __init__( - self, - *, - and_property: Optional[List["_models.BudgetFilterProperties"]] = None, - dimensions: Optional["_models.BudgetComparisonExpression"] = None, - tags: Optional["_models.BudgetComparisonExpression"] = None, - **kwargs - ): - """ - :keyword and_property: The logical "AND" expression. Must have at least 2 items. - :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: Has comparison expression for a tag. - :paramtype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression - """ - super().__init__(**kwargs) - self.and_property = and_property - self.dimensions = dimensions - self.tags = tags - - -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: 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"}, - } - - def __init__( - self, - *, - dimensions: Optional["_models.BudgetComparisonExpression"] = None, - tags: Optional["_models.BudgetComparisonExpression"] = None, - **kwargs - ): - """ - :keyword dimensions: Has comparison expression for a dimension. - :paramtype dimensions: ~azure.mgmt.consumption.models.BudgetComparisonExpression - :keyword tags: Has comparison expression for a tag. - :paramtype tags: ~azure.mgmt.consumption.models.BudgetComparisonExpression - """ - super().__init__(**kwargs) - self.dimensions = dimensions - self.tags = tags - - -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. - - :ivar value: The list of budgets. - :vartype value: list[~azure.mgmt.consumption.models.Budget] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Budget]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -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: 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. - :vartype end_date: ~datetime.datetime - """ - - _validation = { - "start_date": {"required": True}, - } - - _attribute_map = { - "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): - """ - :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().__init__(**kwargs) - self.start_date = start_date - self.end_date = end_date - - -class ChargesListResult(_serialization.Model): - """Result of listing charge summary. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of charge summary. - :vartype value: list[~azure.mgmt.consumption.models.ChargeSummary] - """ - - _validation = { - "value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ChargeSummary]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - - -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 - - 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: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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}, - "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"}, - } - - _subtype_map = {"kind": {"legacy": "LegacyChargeSummary", "modern": "ModernChargeSummary"}} - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -class CreditBalanceSummary(_serialization.Model): - """Summary of credit balances. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar estimated_balance: Estimated balance. - :vartype estimated_balance: ~azure.mgmt.consumption.models.Amount - :ivar current_balance: Current balance. - :vartype current_balance: ~azure.mgmt.consumption.models.Amount - :ivar estimated_balance_in_billing_currency: Estimated balance in billing currency. - :vartype estimated_balance_in_billing_currency: - ~azure.mgmt.consumption.models.AmountWithExchangeRate - """ - - _validation = { - "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", - }, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.estimated_balance = None - self.current_balance = None - self.estimated_balance_in_billing_currency = None - - -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: Resource Id. - :vartype id: str - :ivar name: Resource name. - :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 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. - :vartype pending_credit_adjustments: ~azure.mgmt.consumption.models.Amount - :ivar expired_credit: Expired credit. - :vartype expired_credit: ~azure.mgmt.consumption.models.Amount - :ivar pending_eligible_charges: Pending eligible charges. - :vartype pending_eligible_charges: ~azure.mgmt.consumption.models.Amount - :ivar credit_currency: The credit currency. - :vartype credit_currency: str - :ivar billing_currency: The billing currency. - :vartype billing_currency: str - :ivar reseller: Credit's reseller. - :vartype reseller: ~azure.mgmt.consumption.models.Reseller - :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}, - "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"}, - "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().__init__(e_tag=e_tag, **kwargs) - self.balance_summary = None - self.pending_credit_adjustments = None - self.expired_credit = None - self.pending_eligible_charges = None - self.credit_currency = None - self.billing_currency = None - self.reseller = None - self.e_tag_properties_e_tag = None - - -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. - - :ivar amount: The total amount of cost which is being tracked by the budget. - :vartype amount: float - :ivar unit: The unit of measure for the budget amount. - :vartype unit: str - """ - - _validation = { - "amount": {"readonly": True}, - "unit": {"readonly": True}, - } - - _attribute_map = { - "amount": {"key": "amount", "type": "float"}, - "unit": {"key": "unit", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.amount = None - self.unit = None - - -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. - - :ivar download_url: The link (url) to download the pricesheet. - :vartype download_url: str - :ivar valid_till: Download link validity. - :vartype valid_till: str - """ - - _validation = { - "download_url": {"readonly": True}, - "valid_till": {"readonly": True}, - } - - _attribute_map = { - "download_url": {"key": "downloadUrl", "type": "str"}, - "valid_till": {"key": "validTill", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.download_url = None - self.valid_till = None - - -class ErrorDetails(_serialization.Model): - """The details of the error. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - - -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: - - - * - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. - - * - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. - - :ivar error: The details of the error. - :vartype error: ~azure.mgmt.consumption.models.ErrorDetails - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetails"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): - """ - :keyword error: The details of the error. - :paramtype error: ~azure.mgmt.consumption.models.ErrorDetails - """ - super().__init__(**kwargs) - self.error = error - - -class Events(_serialization.Model): - """Result of listing event summary. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of event summary. - :vartype value: list[~azure.mgmt.consumption.models.EventSummary] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[EventSummary]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -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. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :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 transaction_date: The date of the event. - :vartype transaction_date: ~datetime.datetime - :ivar description: The description of the event. - :vartype description: str - :ivar new_credit: The amount of new credit or commitment for NewCredit or SettleCharges event. - :vartype new_credit: ~azure.mgmt.consumption.models.Amount - :ivar adjustments: The amount of balance adjustment. The property is not available for - ConsumptionCommitment lots. - :vartype adjustments: ~azure.mgmt.consumption.models.Amount - :ivar credit_expired: The amount of expired credit or commitment for NewCredit or SettleCharges - event. - :vartype credit_expired: ~azure.mgmt.consumption.models.Amount - :ivar charges: The amount of charges for events of type SettleCharges and - PendingEligibleCharges. - :vartype charges: ~azure.mgmt.consumption.models.Amount - :ivar closed_balance: The balance after the event. - :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", 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. - :vartype invoice_number: str - :ivar billing_profile_id: The ID that uniquely identifies the billing profile for which the - event happened. The property is only available for billing account of type - MicrosoftCustomerAgreement. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The display name of the billing profile for which the event - happened. The property is only available for billing account of type - MicrosoftCustomerAgreement. - :vartype billing_profile_display_name: str - :ivar lot_id: The ID that uniquely identifies the lot for which the event happened. - :vartype lot_id: str - :ivar lot_source: Identifies the source of the lot for which the event happened. - :vartype lot_source: str - :ivar canceled_credit: Amount of canceled credit. - :vartype canceled_credit: ~azure.mgmt.consumption.models.Amount - :ivar credit_currency: The credit currency of the event. - :vartype credit_currency: str - :ivar billing_currency: The billing currency of the event. - :vartype billing_currency: str - :ivar reseller: The reseller of the event. - :vartype reseller: ~azure.mgmt.consumption.models.Reseller - :ivar credit_expired_in_billing_currency: The amount of expired credit or commitment for - NewCredit or SettleCharges event in billing currency. - :vartype credit_expired_in_billing_currency: - ~azure.mgmt.consumption.models.AmountWithExchangeRate - :ivar new_credit_in_billing_currency: The amount of new credit or commitment for NewCredit or - SettleCharges event in billing currency. - :vartype new_credit_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate - :ivar adjustments_in_billing_currency: The amount of balance adjustment in billing currency. - :vartype adjustments_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate - :ivar charges_in_billing_currency: The amount of charges for events of type SettleCharges and - PendingEligibleCharges in billing currency. - :vartype charges_in_billing_currency: ~azure.mgmt.consumption.models.AmountWithExchangeRate - :ivar closed_balance_in_billing_currency: The balance in billing currency after the event. - :vartype closed_balance_in_billing_currency: - ~azure.mgmt.consumption.models.AmountWithExchangeRate - :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}, - "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__( # 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 - used to determine whether the user is updating the latest version or not. - :paramtype e_tag: str - :keyword event_type: Identifies the type of the event. Known values are: "SettledCharges", - "PendingCharges", "PendingAdjustments", "PendingNewCredit", "PendingExpiredCredit", "UnKnown", - "NewCredit", and "CreditExpired". - :paramtype event_type: str or ~azure.mgmt.consumption.models.EventType - """ - super().__init__(e_tag=e_tag, **kwargs) - self.transaction_date = None - self.description = None - self.new_credit = None - self.adjustments = None - self.credit_expired = None - self.charges = None - self.closed_balance = None - self.event_type = event_type - self.invoice_number = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.lot_id = None - self.lot_source = None - self.canceled_credit = None - self.credit_currency = None - self.billing_currency = None - self.reseller = None - self.credit_expired_in_billing_currency = None - self.new_credit_in_billing_currency = None - self.adjustments_in_billing_currency = None - self.charges_in_billing_currency = None - self.closed_balance_in_billing_currency = None - self.e_tag_properties_e_tag = None - - -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. - - :ivar amount: The forecasted cost for the total time period which is being tracked by the - budget. This value is only provided if the budget contains a forecast alert type. - :vartype amount: float - :ivar unit: The unit of measure for the budget amount. - :vartype unit: str - """ - - _validation = { - "amount": {"readonly": True}, - "unit": {"readonly": True}, - } - - _attribute_map = { - "amount": {"key": "amount", "type": "float"}, - "unit": {"key": "unit", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.amount = None - self.unit = None - - -class HighCasedErrorDetails(_serialization.Model): - """The details of the error. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - - -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: - - - * - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. - - * - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. - - :ivar error: The details of the error. - :vartype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails - """ - - _attribute_map = { - "error": {"key": "error", "type": "HighCasedErrorDetails"}, - } - - def __init__(self, *, error: Optional["_models.HighCasedErrorDetails"] = None, **kwargs): - """ - :keyword error: The details of the error. - :paramtype error: ~azure.mgmt.consumption.models.HighCasedErrorDetails - """ - super().__init__(**kwargs) - self.error = error - - -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: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 - :ivar usage_start: Usage start date. - :vartype usage_start: str - :ivar usage_end: Usage end date. - :vartype usage_end: str - :ivar azure_charges: Azure Charges. - :vartype azure_charges: float - :ivar charges_billed_separately: Charges Billed separately. - :vartype charges_billed_separately: 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}, - "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"}, - "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.azure_marketplace_charges = None - self.currency = None - - -class ResourceAttributes(_serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar location: Resource location. - :vartype location: str - :ivar sku: Resource sku. - :vartype sku: str - """ - - _validation = { - "location": {"readonly": True}, - "sku": {"readonly": True}, - } - - _attribute_map = { - "location": {"key": "location", "type": "str"}, - "sku": {"key": "sku", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.location = None - self.sku = None - - -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 - - 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 sku: Resource sku. - :vartype sku: str - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 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}, - } - - _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"}, - } - - _subtype_map = {"kind": {"legacy": "LegacyReservationRecommendation", "modern": "ModernReservationRecommendation"}} - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.location = None - self.sku = None - self.kind: Optional[str] = None - self.id = None - self.name = None - self.type = None - self.etag = None - self.tags = None - - -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. - - All required parameters must be populated in order to send to Azure. - - :ivar location: Resource location. - :vartype location: str - :ivar sku: Resource sku. - :vartype sku: str - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 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 - :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 resource_type: The azure resource type. - :vartype resource_type: 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: float - :ivar recommended_quantity: Recommended quality for reserved instances. - :vartype recommended_quantity: float - :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. - :vartype total_cost_with_reserved_instances: float - :ivar net_savings: Total estimated savings with reserved instances. - :vartype net_savings: float - :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] - """ - - _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}, - } - - _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().__init__(**kwargs) - self.kind: str = "legacy" - 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.resource_type = None - self.term = None - self.cost_with_no_reserved_instances = None - self.recommended_quantity = None - self.total_cost_with_reserved_instances = None - self.net_savings = None - self.first_usage_date = None - self.scope: str = "legacy" - self.sku_properties = None - - -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 - - 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 look_back_period: The number of days of usage to look back for recommendation. - :vartype look_back_period: str - :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 resource_type: The azure resource type. - :vartype resource_type: 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: float - :ivar recommended_quantity: Recommended quality for reserved instances. - :vartype recommended_quantity: float - :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. - :vartype total_cost_with_reserved_instances: float - :ivar net_savings: Total estimated savings with reserved instances. - :vartype net_savings: float - :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] - """ - - _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}, - } - - _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]"}, - } - - _subtype_map = { - "scope": { - "Shared": "LegacySharedScopeReservationRecommendationProperties", - "Single": "LegacySingleScopeReservationRecommendationProperties", - } - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - 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.resource_type = None - self.term = None - self.cost_with_no_reserved_instances = None - self.recommended_quantity = None - self.total_cost_with_reserved_instances = None - self.net_savings = None - self.first_usage_date = None - self.scope: Optional[str] = None - self.sku_properties = None - - -class ReservationTransactionResource(_serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: Resource tags. - :vartype tags: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "tags": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "tags": {"key": "tags", "type": "[str]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.tags = None - - -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. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: Resource tags. - :vartype tags: list[str] - :ivar event_date: The date of the transaction. - :vartype event_date: ~datetime.datetime - :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 - order contains reservations. The reservation order specifies the VM size and region for the - reservations. - :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 or Refund). - :vartype event_type: str - :ivar quantity: The quantity of the transaction. - :vartype quantity: float - :ivar amount: The charge of the transaction. - :vartype amount: float - :ivar currency: The ISO currency in which the transaction is charged, for example, USD. - :vartype currency: str - :ivar reservation_order_name: The name of the reservation order. - :vartype reservation_order_name: str - :ivar purchasing_enrollment: The purchasing enrollment. - :vartype purchasing_enrollment: str - :ivar purchasing_subscription_guid: The subscription guid that makes the transaction. - :vartype purchasing_subscription_guid: str - :ivar purchasing_subscription_name: The subscription name that makes the transaction. - :vartype purchasing_subscription_name: str - :ivar arm_sku_name: This is the ARM Sku name. It can be used to join with the serviceType field - in additional info in usage records. - :vartype arm_sku_name: str - :ivar term: This is the term of the transaction. - :vartype term: str - :ivar region: The region of the transaction. - :vartype region: str - :ivar account_name: The name of the account that makes the transaction. - :vartype account_name: str - :ivar account_owner_email: The email of the account owner that makes the transaction. - :vartype account_owner_email: str - :ivar department_name: The department name. - :vartype department_name: str - :ivar cost_center: The cost center of this department if it is a department and a cost center - is provided. - :vartype cost_center: str - :ivar current_enrollment: The current enrollment. - :vartype current_enrollment: str - :ivar billing_frequency: The billing frequency, which can be either one-time or recurring. - :vartype billing_frequency: str - :ivar billing_month: The billing month(yyyyMMdd), on which the event initiated. - :vartype billing_month: int - :ivar monetary_commitment: The monetary commitment amount at the enrollment scope. - :vartype monetary_commitment: float - :ivar overage: The overage amount at the enrollment scope. - :vartype overage: float - """ - - _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}, - } - - _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): # pylint: disable=too-many-locals - """ """ - super().__init__(**kwargs) - self.event_date = None - self.reservation_order_id = None - self.description = None - self.event_type = None - self.quantity = None - self.amount = None - self.currency = None - self.reservation_order_name = None - self.purchasing_enrollment = None - self.purchasing_subscription_guid = None - self.purchasing_subscription_name = None - self.arm_sku_name = None - self.term = None - self.region = None - self.account_name = None - self.account_owner_email = None - self.department_name = None - self.cost_center = None - self.current_enrollment = None - self.billing_frequency = None - self.billing_month = None - self.monetary_commitment = None - self.overage = None - - -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. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: Resource tags. - :vartype tags: list[str] - :ivar event_date: The date of the transaction. - :vartype event_date: ~datetime.datetime - :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 - order contains reservations. The reservation order specifies the VM size and region for the - reservations. - :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 or Refund). - :vartype event_type: str - :ivar quantity: The quantity of the transaction. - :vartype quantity: float - :ivar amount: The charge of the transaction. - :vartype amount: float - :ivar currency: The ISO currency in which the transaction is charged, for example, USD. - :vartype currency: str - :ivar reservation_order_name: The name of the reservation order. - :vartype reservation_order_name: str - :ivar purchasing_enrollment: The purchasing enrollment. - :vartype purchasing_enrollment: str - :ivar purchasing_subscription_guid: The subscription guid that makes the transaction. - :vartype purchasing_subscription_guid: str - :ivar purchasing_subscription_name: The subscription name that makes the transaction. - :vartype purchasing_subscription_name: str - :ivar arm_sku_name: This is the ARM Sku name. It can be used to join with the serviceType field - in additional info in usage records. - :vartype arm_sku_name: str - :ivar term: This is the term of the transaction. - :vartype term: str - :ivar region: The region of the transaction. - :vartype region: str - :ivar account_name: The name of the account that makes the transaction. - :vartype account_name: str - :ivar account_owner_email: The email of the account owner that makes the transaction. - :vartype account_owner_email: str - :ivar department_name: The department name. - :vartype department_name: str - :ivar cost_center: The cost center of this department if it is a department and a cost center - is provided. - :vartype cost_center: str - :ivar current_enrollment: The current enrollment. - :vartype current_enrollment: str - :ivar billing_frequency: The billing frequency, which can be either one-time or recurring. - :vartype billing_frequency: str - :ivar billing_month: The billing month(yyyyMMdd), on which the event initiated. - :vartype billing_month: int - :ivar monetary_commitment: The monetary commitment amount at the enrollment scope. - :vartype monetary_commitment: float - :ivar overage: The overage amount at the enrollment scope. - :vartype overage: float - """ - - _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}, - } - - _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): # 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. - - All required parameters must be populated in order to send to Azure. - - :ivar look_back_period: The number of days of usage to look back for recommendation. - :vartype look_back_period: str - :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 resource_type: The azure resource type. - :vartype resource_type: 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: float - :ivar recommended_quantity: Recommended quality for reserved instances. - :vartype recommended_quantity: float - :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. - :vartype total_cost_with_reserved_instances: float - :ivar net_savings: Total estimated savings with reserved instances. - :vartype net_savings: float - :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] - """ - - _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}, - } - - _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().__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. - - All required parameters must be populated in order to send to Azure. - - :ivar look_back_period: The number of days of usage to look back for recommendation. - :vartype look_back_period: str - :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 resource_type: The azure resource type. - :vartype resource_type: 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: float - :ivar recommended_quantity: Recommended quality for reserved instances. - :vartype recommended_quantity: float - :ivar total_cost_with_reserved_instances: The total amount of cost with reserved instances. - :vartype total_cost_with_reserved_instances: float - :ivar net_savings: Total estimated savings with reserved instances. - :vartype net_savings: float - :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 subscription_id: Subscription id associated with single scoped recommendation. - :vartype subscription_id: str - """ - - _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}, - } - - _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().__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 - - 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: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 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}, - } - - _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"}, - } - - _subtype_map = {"kind": {"legacy": "LegacyUsageDetail", "modern": "ModernUsageDetail"}} - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.kind: Optional[str] = None - - -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. - - All required parameters must be populated in order to send to Azure. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 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 billing_account_name: Billing Account Name. - :vartype billing_account_name: str - :ivar billing_period_start_date: The billing period start date. - :vartype billing_period_start_date: ~datetime.datetime - :ivar billing_period_end_date: The billing period end date. - :vartype billing_period_end_date: ~datetime.datetime - :ivar billing_profile_id: Billing Profile identifier. - :vartype billing_profile_id: str - :ivar billing_profile_name: Billing Profile Name. - :vartype billing_profile_name: str - :ivar account_owner_id: Account Owner Id. - :vartype account_owner_id: str - :ivar account_name: Account Name. - :vartype account_name: str - :ivar subscription_id: Subscription guid. - :vartype subscription_id: str - :ivar subscription_name: Subscription name. - :vartype subscription_name: str - :ivar date: Date for the usage record. - :vartype date: ~datetime.datetime - :ivar product: Product name for the consumed service or purchase. Not available for - Marketplace. - :vartype product: str - :ivar part_number: Part Number of the service used. Can be used to join with the price sheet. - Not available for marketplace. - :vartype part_number: str - :ivar meter_id: The meter id (GUID). Not available for marketplace. For reserved instance this - represents the primary meter for which the reservation was purchased. For the actual VM Size - for which the reservation is purchased see productOrderName. - :vartype meter_id: str - :ivar meter_details: The details about the meter. By default this is not populated, unless it's - specified in $expand. - :vartype meter_details: ~azure.mgmt.consumption.models.MeterDetailsResponse - :ivar quantity: The usage quantity. - :vartype quantity: float - :ivar effective_price: Effective Price that's charged for the usage. - :vartype effective_price: float - :ivar cost: The amount of cost before tax. - :vartype cost: float - :ivar unit_price: Unit Price is the price applicable to you. (your EA or other contract price). - :vartype unit_price: float - :ivar billing_currency: Billing Currency. - :vartype billing_currency: str - :ivar resource_location: Resource Location. - :vartype resource_location: str - :ivar consumed_service: Consumed service name. Name of the azure resource provider that emits - the usage or was purchased. This value is not provided for marketplace usage. - :vartype consumed_service: str - :ivar resource_id: Unique identifier of the Azure Resource Manager usage detail resource. - :vartype resource_id: str - :ivar resource_name: Resource Name. - :vartype resource_name: str - :ivar service_info1: Service-specific metadata. - :vartype service_info1: str - :ivar service_info2: Legacy field with optional service-specific metadata. - :vartype service_info2: str - :ivar additional_info: Additional details of this usage item. By default this is not populated, - unless it's specified in $expand. Use this field to get usage line item specific details such - as the actual VM Size (ServiceType) or the ratio in which the reservation discount is applied. - :vartype additional_info: str - :ivar invoice_section: Invoice Section Name. - :vartype invoice_section: str - :ivar cost_center: The cost center of this department if it is a department and a cost center - is provided. - :vartype cost_center: str - :ivar resource_group: Resource Group Name. - :vartype resource_group: str - :ivar reservation_id: ARM resource id of the reservation. Only applies to records relevant to - reservations. - :vartype reservation_id: str - :ivar reservation_name: User provided display name of the reservation. Last known name for a - particular day is populated in the daily data. Only applies to records relevant to - reservations. - :vartype reservation_name: str - :ivar product_order_id: Product Order Id. For reservations this is the Reservation Order ID. - :vartype product_order_id: str - :ivar product_order_name: Product Order Name. For reservations this is the SKU that was - purchased. - :vartype product_order_name: str - :ivar offer_id: Offer Id. Ex: MS-AZR-0017P, MS-AZR-0148P. - :vartype offer_id: str - :ivar is_azure_credit_eligible: Is Azure Credit Eligible. - :vartype is_azure_credit_eligible: bool - :ivar term: Term (in months). 1 month for monthly recurring purchase. 12 months for a 1 year - reservation. 36 months for a 3 year reservation. - :vartype term: str - :ivar publisher_name: Publisher Name. - :vartype publisher_name: str - :ivar publisher_type: Publisher Type. - :vartype publisher_type: str - :ivar plan_name: Plan Name. - :vartype plan_name: str - :ivar charge_type: Indicates a charge represents credits, usage, a Marketplace purchase, a - reservation fee, or a refund. - :vartype charge_type: str - :ivar frequency: Indicates how frequently this charge will occur. OneTime for purchases which - only happen once, Monthly for fees which recur every month, and UsageBased for charges based on - how much a service is used. - :vartype frequency: str - :ivar pay_g_price: Retail price for the resource. - :vartype pay_g_price: float - :ivar benefit_id: Unique identifier for the applicable benefit. - :vartype benefit_id: str - :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", 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}, - } - - _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): # 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 - self.billing_period_end_date = None - self.billing_profile_id = None - self.billing_profile_name = None - self.account_owner_id = None - self.account_name = None - self.subscription_id = None - self.subscription_name = None - self.date = None - self.product = None - self.part_number = None - self.meter_id = None - self.meter_details = None - self.quantity = None - self.effective_price = None - self.cost = None - self.unit_price = None - self.billing_currency = None - self.resource_location = None - self.consumed_service = None - self.resource_id = None - self.resource_name = None - self.service_info1 = None - self.service_info2 = None - self.additional_info = None - self.invoice_section = None - self.cost_center = None - self.resource_group = None - self.reservation_id = None - self.reservation_name = None - self.product_order_id = None - self.product_order_name = None - self.offer_id = None - self.is_azure_credit_eligible = None - self.term = None - self.publisher_name = None - self.publisher_type = None - self.plan_name = None - self.charge_type = None - self.frequency = None - self.pay_g_price = None - self.benefit_id = None - self.benefit_name = None - self.pricing_model = None - - -class Lots(_serialization.Model): - """Result of listing lot summary. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of lot summary. - :vartype value: list[~azure.mgmt.consumption.models.LotSummary] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[LotSummary]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -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. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :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 original_amount: The original amount of a lot. - :vartype original_amount: ~azure.mgmt.consumption.models.Amount - :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", - 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 - :ivar expiration_date: The expiration date of a lot. - :vartype expiration_date: ~datetime.datetime - :ivar po_number: The po number of the invoice on which the lot was added. This property is not - available for ConsumptionCommitment lots. - :vartype po_number: str - :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", and "Canceled". - :vartype status: str or ~azure.mgmt.consumption.models.Status - :ivar credit_currency: The currency of the lot. - :vartype credit_currency: str - :ivar billing_currency: The billing currency of the lot. - :vartype billing_currency: str - :ivar original_amount_in_billing_currency: The original amount of a lot in billing currency. - :vartype original_amount_in_billing_currency: - ~azure.mgmt.consumption.models.AmountWithExchangeRate - :ivar closed_balance_in_billing_currency: The balance as of the last invoice in billing - currency. - :vartype closed_balance_in_billing_currency: - ~azure.mgmt.consumption.models.AmountWithExchangeRate - :ivar reseller: The reseller of the lot. - :vartype reseller: ~azure.mgmt.consumption.models.Reseller - :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}, - "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): - """ - :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :paramtype e_tag: str - """ - super().__init__(e_tag=e_tag, **kwargs) - self.original_amount = None - self.closed_balance = None - self.source = None - self.start_date = None - self.expiration_date = None - self.po_number = None - self.purchased_date = None - self.status = None - self.credit_currency = None - self.billing_currency = None - self.original_amount_in_billing_currency = None - self.closed_balance_in_billing_currency = None - self.reseller = None - self.e_tag_properties_e_tag = None - - -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. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :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. - :vartype billing_period_id: str - :ivar usage_start: The start of the date time range covered by aggregated cost. - :vartype usage_start: ~datetime.datetime - :ivar usage_end: The end of the date time range covered by the aggregated cost. - :vartype usage_end: ~datetime.datetime - :ivar azure_charges: Azure Charges. - :vartype azure_charges: float - :ivar marketplace_charges: Marketplace Charges. - :vartype marketplace_charges: float - :ivar charges_billed_separately: Charges Billed Separately. - :vartype charges_billed_separately: float - :ivar currency: The ISO currency in which the meter is charged, for example, USD. - :vartype currency: str - :ivar children: Children of a management group. - :vartype children: list[~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult] - :ivar included_subscriptions: List of subscription Guids included in the calculation of - aggregated cost. - :vartype included_subscriptions: list[str] - :ivar excluded_subscriptions: List of subscription Guids excluded from the calculation of - aggregated cost. - :vartype excluded_subscriptions: list[str] - """ - - _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}, - } - - _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]"}, - } - - def __init__( - self, - *, - children: Optional[List["_models.ManagementGroupAggregatedCostResult"]] = None, - included_subscriptions: Optional[List[str]] = None, - excluded_subscriptions: Optional[List[str]] = None, - **kwargs - ): - """ - :keyword children: Children of a management group. - :paramtype children: list[~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult] - :keyword included_subscriptions: List of subscription Guids included in the calculation of - aggregated cost. - :paramtype included_subscriptions: list[str] - :keyword excluded_subscriptions: List of subscription Guids excluded from the calculation of - aggregated cost. - :paramtype excluded_subscriptions: list[str] - """ - super().__init__(**kwargs) - self.billing_period_id = None - self.usage_start = None - self.usage_end = None - self.azure_charges = None - self.marketplace_charges = None - self.charges_billed_separately = None - self.currency = None - self.children = children - self.included_subscriptions = included_subscriptions - self.excluded_subscriptions = excluded_subscriptions - - -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. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :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 - :ivar usage_start: The start of the date time range covered by the usage detail. - :vartype usage_start: ~datetime.datetime - :ivar usage_end: The end of the date time range covered by the usage detail. - :vartype usage_end: ~datetime.datetime - :ivar resource_rate: The marketplace resource rate. - :vartype resource_rate: float - :ivar offer_name: The type of offer. - :vartype offer_name: str - :ivar resource_group: The name of resource group. - :vartype resource_group: str - :ivar additional_info: Additional information. - :vartype additional_info: str - :ivar order_number: The order number. - :vartype order_number: str - :ivar instance_name: The name of the resource instance that the usage is about. - :vartype instance_name: str - :ivar instance_id: The uri of the resource instance that the usage is about. - :vartype instance_id: str - :ivar currency: The ISO currency in which the meter is charged, for example, USD. - :vartype currency: str - :ivar consumed_quantity: The quantity of usage. - :vartype consumed_quantity: float - :ivar unit_of_measure: The unit of measure. - :vartype unit_of_measure: str - :ivar pretax_cost: The amount of cost before tax. - :vartype pretax_cost: float - :ivar is_estimated: The estimated usage is subject to change. - :vartype is_estimated: bool - :ivar meter_id: The meter id (GUID). - :vartype meter_id: str - :ivar subscription_guid: Subscription guid. - :vartype subscription_guid: str - :ivar subscription_name: Subscription name. - :vartype subscription_name: str - :ivar account_name: Account name. - :vartype account_name: str - :ivar department_name: Department name. - :vartype department_name: str - :ivar consumed_service: Consumed service name. - :vartype consumed_service: str - :ivar cost_center: The cost center of this department if it is a department and a costcenter - exists. - :vartype cost_center: str - :ivar additional_properties: Additional details of this usage item. By default this is not - populated, unless it's specified in $expand. - :vartype additional_properties: str - :ivar publisher_name: The name of publisher. - :vartype publisher_name: str - :ivar plan_name: The name of plan. - :vartype plan_name: str - :ivar is_recurring_charge: Flag indicating whether this is a recurring charge or not. - :vartype is_recurring_charge: bool - """ - - _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}, - } - - _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): # pylint: disable=too-many-locals - """ """ - super().__init__(**kwargs) - self.billing_period_id = None - self.usage_start = None - self.usage_end = None - self.resource_rate = None - self.offer_name = None - self.resource_group = None - self.additional_info = None - self.order_number = None - self.instance_name = None - self.instance_id = None - self.currency = None - self.consumed_quantity = None - self.unit_of_measure = None - self.pretax_cost = None - self.is_estimated = None - self.meter_id = None - self.subscription_guid = None - self.subscription_name = None - self.account_name = None - self.department_name = None - self.consumed_service = None - self.cost_center = None - self.additional_properties = None - self.publisher_name = None - self.plan_name = None - self.is_recurring_charge = None - - -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. - - :ivar value: The list of marketplaces. - :vartype value: list[~azure.mgmt.consumption.models.Marketplace] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Marketplace]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -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. - - :ivar meter_name: The name of the meter, within the given meter category. - :vartype meter_name: str - :ivar meter_category: The category of the meter, for example, 'Cloud services', 'Networking', - etc.. - :vartype meter_category: str - :ivar meter_sub_category: The subcategory of the meter, for example, 'A6 Cloud services', - 'ExpressRoute (IXP)', etc.. - :vartype meter_sub_category: str - :ivar unit: The unit in which the meter consumption is charged, for example, 'Hours', 'GB', - etc. - :vartype unit: str - :ivar meter_location: The location in which the Azure service is available. - :vartype meter_location: str - :ivar total_included_quantity: The total included quantity associated with the offer. - :vartype total_included_quantity: float - :ivar pretax_standard_rate: The pretax listing price. - :vartype pretax_standard_rate: float - :ivar service_name: The name of the service. - :vartype service_name: str - :ivar service_tier: The service tier. - :vartype service_tier: str - """ - - _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}, - } - - _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().__init__(**kwargs) - self.meter_name = None - self.meter_category = None - self.meter_sub_category = None - self.unit = None - self.meter_location = None - self.total_included_quantity = None - self.pretax_standard_rate = None - self.service_name = None - self.service_tier = None - - -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. - - :ivar meter_name: The name of the meter, within the given meter category. - :vartype meter_name: str - :ivar meter_category: The category of the meter, for example, 'Cloud services', 'Networking', - etc.. - :vartype meter_category: str - :ivar meter_sub_category: The subcategory of the meter, for example, 'A6 Cloud services', - 'ExpressRoute (IXP)', etc.. - :vartype meter_sub_category: str - :ivar unit_of_measure: The unit in which the meter consumption is charged, for example, - 'Hours', 'GB', etc. - :vartype unit_of_measure: str - :ivar service_family: The service family. - :vartype service_family: str - """ - - _validation = { - "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"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.meter_name = None - self.meter_category = None - self.meter_sub_category = None - self.unit_of_measure = None - self.service_family = None - - -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: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 - :ivar usage_start: Usage start date. - :vartype usage_start: str - :ivar usage_end: Usage end date. - :vartype usage_end: str - :ivar azure_charges: Azure Charges. - :vartype azure_charges: ~azure.mgmt.consumption.models.Amount - :ivar charges_billed_separately: Charges Billed separately. - :vartype charges_billed_separately: ~azure.mgmt.consumption.models.Amount - :ivar marketplace_charges: Marketplace Charges. - :vartype marketplace_charges: ~azure.mgmt.consumption.models.Amount - :ivar billing_account_id: Billing Account Id. - :vartype billing_account_id: str - :ivar billing_profile_id: Billing Profile Id. - :vartype billing_profile_id: str - :ivar invoice_section_id: Invoice Section Id. - :vartype invoice_section_id: str - :ivar customer_id: Customer Id. - :vartype customer_id: str - :ivar is_invoiced: Is charge Invoiced. - :vartype is_invoiced: bool - """ - - _validation = { - "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"}, - "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 - self.azure_charges = None - self.charges_billed_separately = None - self.marketplace_charges = None - self.billing_account_id = None - self.billing_profile_id = None - self.invoice_section_id = None - self.customer_id = None - self.is_invoiced = None - - -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. - - All required parameters must be populated in order to send to Azure. - - :ivar location: Resource location. - :vartype location: str - :ivar sku: Resource sku. - :vartype sku: str - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 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 - :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}, - "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"}, - "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}, - } - - _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 - 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: Optional[str] = None - self.sku_properties = None - self.sku_name = None - - -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. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: Resource tags. - :vartype tags: list[str] - :ivar amount: The charge of the transaction. - :vartype amount: float - :ivar arm_sku_name: This is the ARM Sku name. It can be used to join with the serviceType field - in additional info in usage records. - :vartype arm_sku_name: str - :ivar billing_frequency: The billing frequency, which can be either one-time or recurring. - :vartype billing_frequency: str - :ivar billing_profile_id: Billing profile Id. - :vartype billing_profile_id: str - :ivar billing_profile_name: Billing profile name. - :vartype billing_profile_name: str - :ivar currency: The ISO currency in which the transaction is charged, for example, USD. - :vartype currency: str - :ivar description: The description of the transaction. - :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 or Refund). - :vartype event_type: str - :ivar invoice: Invoice Number. - :vartype invoice: str - :ivar invoice_id: Invoice Id as on the invoice where the specific transaction appears. - :vartype invoice_id: str - :ivar invoice_section_id: Invoice Section Id. - :vartype invoice_section_id: str - :ivar invoice_section_name: Invoice Section Name. - :vartype invoice_section_name: str - :ivar purchasing_subscription_guid: The subscription guid that makes the transaction. - :vartype purchasing_subscription_guid: str - :ivar purchasing_subscription_name: The subscription name that makes the transaction. - :vartype purchasing_subscription_name: str - :ivar quantity: The quantity of the transaction. - :vartype quantity: float - :ivar region: The region of the transaction. - :vartype region: 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 - order contains reservations. The reservation order specifies the VM size and region for the - reservations. - :vartype reservation_order_id: str - :ivar reservation_order_name: The name of the reservation order. - :vartype reservation_order_name: str - :ivar term: This is the term of the transaction. - :vartype term: str - """ - - _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}, - } - - _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): # pylint: disable=too-many-locals - """ """ - super().__init__(**kwargs) - self.amount = None - self.arm_sku_name = None - self.billing_frequency = None - self.billing_profile_id = None - self.billing_profile_name = None - self.currency = None - self.description = None - self.event_date = None - self.event_type = None - self.invoice = None - self.invoice_id = None - self.invoice_section_id = None - self.invoice_section_name = None - self.purchasing_subscription_guid = None - self.purchasing_subscription_name = None - self.quantity = None - self.region = None - self.reservation_order_id = None - self.reservation_order_name = None - self.term = None - - -class ModernReservationTransactionsListResult(_serialization.Model): - """Result of listing reservation recommendations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of reservation recommendations. - :vartype value: list[~azure.mgmt.consumption.models.ModernReservationTransaction] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ModernReservationTransaction]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -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. - - All required parameters must be populated in order to send to Azure. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :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 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", 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 - :ivar billing_period_start_date: Billing Period Start Date as in the invoice. - :vartype billing_period_start_date: ~datetime.datetime - :ivar billing_period_end_date: Billing Period End Date as in the invoice. - :vartype billing_period_end_date: ~datetime.datetime - :ivar billing_profile_id: Identifier for the billing profile that groups costs across invoices - in the a singular billing currency across across the customers who have onboarded the Microsoft - customer agreement and the customers in CSP who have made entitlement purchases like SaaS, - Marketplace, RI, etc. - :vartype billing_profile_id: str - :ivar billing_profile_name: Name of the billing profile that groups costs across invoices in - the a singular billing currency across across the customers who have onboarded the Microsoft - customer agreement and the customers in CSP who have made entitlement purchases like SaaS, - Marketplace, RI, etc. - :vartype billing_profile_name: str - :ivar subscription_guid: Unique Microsoft generated identifier for the Azure Subscription. - :vartype subscription_guid: str - :ivar subscription_name: Name of the Azure Subscription. - :vartype subscription_name: str - :ivar date: Date for the usage record. - :vartype date: ~datetime.datetime - :ivar product: Name of the product that has accrued charges by consumption or purchase as - listed in the invoice. Not available for Marketplace. - :vartype product: str - :ivar meter_id: The meter id (GUID). Not available for marketplace. For reserved instance this - represents the primary meter for which the reservation was purchased. For the actual VM Size - for which the reservation is purchased see productOrderName. - :vartype meter_id: str - :ivar meter_name: Identifies the name of the meter against which consumption is measured. - :vartype meter_name: str - :ivar meter_region: Identifies the location of the datacenter for certain services that are - priced based on datacenter location. - :vartype meter_region: str - :ivar meter_category: Identifies the top-level service for the usage. - :vartype meter_category: str - :ivar meter_sub_category: Defines the type or sub-category of Azure service that can affect the - rate. - :vartype meter_sub_category: str - :ivar service_family: List the service family for the product purchased or charged (Example: - Storage ; Compute). - :vartype service_family: str - :ivar quantity: Measure the quantity purchased or consumed.The amount of the meter used during - the billing period. - :vartype quantity: float - :ivar unit_of_measure: Identifies the Unit that the service is charged in. For example, GB, - hours, 10,000 s. - :vartype unit_of_measure: str - :ivar instance_name: Instance Name. - :vartype instance_name: str - :ivar cost_in_usd: Estimated extendedCost or blended cost before tax in USD. - :vartype cost_in_usd: float - :ivar unit_price: Unit Price is the price applicable to you. (your EA or other contract price). - :vartype unit_price: float - :ivar billing_currency_code: The currency defining the billed cost. - :vartype billing_currency_code: str - :ivar resource_location: Name of the resource location. - :vartype resource_location: str - :ivar consumed_service: Consumed service name. Name of the azure resource provider that emits - the usage or was purchased. This value is not provided for marketplace usage. - :vartype consumed_service: str - :ivar service_info1: Service-specific metadata. - :vartype service_info1: str - :ivar service_info2: Legacy field with optional service-specific metadata. - :vartype service_info2: str - :ivar additional_info: Additional details of this usage item. Use this field to get usage line - item specific details such as the actual VM Size (ServiceType) or the ratio in which the - reservation discount is applied. - :vartype additional_info: str - :ivar invoice_section_id: Identifier of the project that is being charged in the invoice. Not - applicable for Microsoft Customer Agreements onboarded by partners. - :vartype invoice_section_id: str - :ivar invoice_section_name: Name of the project that is being charged in the invoice. Not - applicable for Microsoft Customer Agreements onboarded by partners. - :vartype invoice_section_name: str - :ivar cost_center: The cost center of this department if it is a department and a cost center - is provided. - :vartype cost_center: str - :ivar resource_group: Name of the Azure resource group used for cohesive lifecycle management - of resources. - :vartype resource_group: str - :ivar reservation_id: ARM resource id of the reservation. Only applies to records relevant to - reservations. - :vartype reservation_id: str - :ivar reservation_name: User provided display name of the reservation. Last known name for a - particular day is populated in the daily data. Only applies to records relevant to - reservations. - :vartype reservation_name: str - :ivar product_order_id: The identifier for the asset or Azure plan name that the subscription - belongs to. For example: Azure Plan. For reservations this is the Reservation Order ID. - :vartype product_order_id: str - :ivar product_order_name: Product Order Name. For reservations this is the SKU that was - purchased. - :vartype product_order_name: str - :ivar is_azure_credit_eligible: Determines if the cost is eligible to be paid for using Azure - credits. - :vartype is_azure_credit_eligible: bool - :ivar term: Term (in months). Displays the term for the validity of the offer. For example. In - case of reserved instances it displays 12 months for yearly term of reserved instance. For one - time purchases or recurring purchases, the terms displays 1 month; This is not applicable for - Azure consumption. - :vartype term: str - :ivar publisher_name: Name of the publisher of the service including Microsoft or Third Party - publishers. - :vartype publisher_name: str - :ivar publisher_type: Type of publisher that identifies if the publisher is first party, third - party reseller or third party agency. - :vartype publisher_type: str - :ivar charge_type: Indicates a charge represents credits, usage, a Marketplace purchase, a - reservation fee, or a refund. - :vartype charge_type: str - :ivar frequency: Indicates how frequently this charge will occur. OneTime for purchases which - only happen once, Monthly for fees which recur every month, and UsageBased for charges based on - how much a service is used. - :vartype frequency: str - :ivar cost_in_billing_currency: ExtendedCost or blended cost before tax in billed currency. - :vartype cost_in_billing_currency: float - :ivar cost_in_pricing_currency: ExtendedCost or blended cost before tax in pricing currency to - correlate with prices. - :vartype cost_in_pricing_currency: float - :ivar exchange_rate: Exchange rate used in conversion from pricing currency to billing - currency. - :vartype exchange_rate: str - :ivar exchange_rate_date: Date on which exchange rate used in conversion from pricing currency - to billing currency. - :vartype exchange_rate_date: ~datetime.datetime - :ivar invoice_id: Invoice ID as on the invoice where the specific transaction appears. - :vartype invoice_id: str - :ivar previous_invoice_id: Reference to an original invoice there is a refund (negative cost). - This is populated only when there is a refund. - :vartype previous_invoice_id: str - :ivar pricing_currency_code: Pricing Billing Currency. - :vartype pricing_currency_code: str - :ivar product_identifier: Identifier for the product that has accrued charges by consumption or - purchase . This is the concatenated key of productId and SkuId in partner center. - :vartype product_identifier: str - :ivar resource_location_normalized: Resource Location Normalized. - :vartype resource_location_normalized: str - :ivar service_period_start_date: Start date for the rating period when the service usage was - rated for charges. The prices for Azure services are determined for the rating period. - :vartype service_period_start_date: ~datetime.datetime - :ivar service_period_end_date: End date for the period when the service usage was rated for - charges. The prices for Azure services are determined based on the rating period. - :vartype service_period_end_date: ~datetime.datetime - :ivar customer_tenant_id: Identifier of the customer's AAD tenant. - :vartype customer_tenant_id: str - :ivar customer_name: Name of the customer's AAD tenant. - :vartype customer_name: str - :ivar partner_tenant_id: Identifier for the partner's AAD tenant. - :vartype partner_tenant_id: str - :ivar partner_name: Name of the partner' AAD tenant. - :vartype partner_name: str - :ivar reseller_mpn_id: MPNId for the reseller associated with the subscription. - :vartype reseller_mpn_id: str - :ivar reseller_name: Reseller Name. - :vartype reseller_name: str - :ivar publisher_id: Publisher Id. - :vartype publisher_id: str - :ivar market_price: Market Price that's charged for the usage. - :vartype market_price: float - :ivar exchange_rate_pricing_to_billing: Exchange Rate from pricing currency to billing - currency. - :vartype exchange_rate_pricing_to_billing: float - :ivar payg_cost_in_billing_currency: The amount of PayG cost before tax in billing currency. - :vartype payg_cost_in_billing_currency: float - :ivar payg_cost_in_usd: The amount of PayG cost before tax in US Dollar currency. - :vartype payg_cost_in_usd: float - :ivar partner_earned_credit_rate: Rate of discount applied if there is a partner earned credit - (PEC) based on partner admin link access. - :vartype partner_earned_credit_rate: float - :ivar partner_earned_credit_applied: Flag to indicate if partner earned credit has been applied - or not. - :vartype partner_earned_credit_applied: str - :ivar pay_g_price: Retail price for the resource. - :vartype pay_g_price: float - :ivar benefit_id: Unique identifier for the applicable benefit. - :vartype benefit_id: str - :ivar benefit_name: Name of the applicable benefit. - :vartype benefit_name: str - :ivar provider: Identifier for Product Category or Line Of Business, Ex - Azure, Microsoft 365, - AWS e.t.c. - :vartype provider: str - :ivar cost_allocation_rule_name: Name for Cost Allocation Rule. - :vartype cost_allocation_rule_name: str - """ - - _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}, - } - - _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): # 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 - self.billing_account_name = None - self.billing_period_start_date = None - self.billing_period_end_date = None - self.billing_profile_id = None - self.billing_profile_name = None - self.subscription_guid = None - self.subscription_name = None - self.date = None - self.product = None - self.meter_id = None - self.meter_name = None - self.meter_region = None - self.meter_category = None - self.meter_sub_category = None - self.service_family = None - self.quantity = None - self.unit_of_measure = None - self.instance_name = None - self.cost_in_usd = None - self.unit_price = None - self.billing_currency_code = None - self.resource_location = None - self.consumed_service = None - self.service_info1 = None - self.service_info2 = None - self.additional_info = None - self.invoice_section_id = None - self.invoice_section_name = None - self.cost_center = None - self.resource_group = None - self.reservation_id = None - self.reservation_name = None - self.product_order_id = None - self.product_order_name = None - self.is_azure_credit_eligible = None - self.term = None - self.publisher_name = None - self.publisher_type = None - self.charge_type = None - self.frequency = None - self.cost_in_billing_currency = None - self.cost_in_pricing_currency = None - self.exchange_rate = None - self.exchange_rate_date = None - self.invoice_id = None - self.previous_invoice_id = None - self.pricing_currency_code = None - self.product_identifier = None - self.resource_location_normalized = None - self.service_period_start_date = None - self.service_period_end_date = None - self.customer_tenant_id = None - self.customer_name = None - self.partner_tenant_id = None - self.partner_name = None - self.reseller_mpn_id = None - self.reseller_name = None - self.publisher_id = None - self.market_price = None - self.exchange_rate_pricing_to_billing = None - self.payg_cost_in_billing_currency = None - self.payg_cost_in_usd = None - self.partner_earned_credit_rate = None - self.partner_earned_credit_applied = None - self.pay_g_price = None - self.benefit_id = None - self.benefit_name = None - self.provider = None - self.cost_allocation_rule_name = None - - -class Notification(_serialization.Model): - """The notification associated with a budget. - - All required parameters must be populated in order to send to Azure. - - :ivar enabled: The notification is enabled or not. Required. - :vartype enabled: bool - :ivar operator: The comparison operator. Required. Known values are: "EqualTo", "GreaterThan", - and "GreaterThanOrEqualTo". - :vartype operator: str or ~azure.mgmt.consumption.models.OperatorType - :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: 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. - :vartype contact_roles: list[str] - :ivar contact_groups: Action groups to send the budget notification to when the threshold is - 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" 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", 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}, - } - - _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"}, - } - - def __init__( - self, - *, - enabled: bool, - operator: Union[str, "_models.OperatorType"], - threshold: float, - contact_emails: List[str], - contact_roles: Optional[List[str]] = None, - contact_groups: Optional[List[str]] = None, - threshold_type: Union[str, "_models.ThresholdType"] = "Actual", - locale: Optional[Union[str, "_models.CultureCode"]] = None, - **kwargs - ): - """ - :keyword enabled: The notification is enabled or not. Required. - :paramtype enabled: bool - :keyword operator: The comparison operator. Required. Known values are: "EqualTo", - "GreaterThan", and "GreaterThanOrEqualTo". - :paramtype operator: str or ~azure.mgmt.consumption.models.OperatorType - :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: 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. - :paramtype contact_emails: list[str] - :keyword contact_roles: Contact roles to send the budget notification to when the threshold is - exceeded. - :paramtype contact_roles: list[str] - :keyword contact_groups: Action groups to send the budget notification to when the threshold is - 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" 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", and - "sv-se". - :paramtype locale: str or ~azure.mgmt.consumption.models.CultureCode - """ - super().__init__(**kwargs) - self.enabled = enabled - self.operator = operator - self.threshold = threshold - self.contact_emails = contact_emails - self.contact_roles = contact_roles - self.contact_groups = contact_groups - self.threshold_type = threshold_type - self.locale = locale - - -class Operation(_serialization.Model): - """A Consumption REST API operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Operation Id. - :vartype id: str - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar display: The object that represents the operation. - :vartype display: ~azure.mgmt.consumption.models.OperationDisplay - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplay"}, - } - - def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): - """ - :keyword display: The object that represents the operation. - :paramtype display: ~azure.mgmt.consumption.models.OperationDisplay - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.display = display - - -class OperationDisplay(_serialization.Model): - """The object that represents the operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: Service provider: Microsoft.Consumption. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: UsageDetail, etc. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - :ivar description: Description of the operation. - :vartype description: str - """ - - _validation = { - "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"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None - - -class OperationListResult(_serialization.Model): - """Result of listing 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. - - :ivar value: List of consumption operations supported by the Microsoft.Consumption resource - provider. - :vartype value: list[~azure.mgmt.consumption.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -class PriceSheetProperties(_serialization.Model): - """The properties of the price sheet. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar billing_period_id: The id of the billing period resource that the usage belongs to. - :vartype billing_period_id: str - :ivar meter_id: The meter id (GUID). - :vartype meter_id: str - :ivar meter_details: The details about the meter. By default this is not populated, unless it's - specified in $expand. - :vartype meter_details: ~azure.mgmt.consumption.models.MeterDetails - :ivar unit_of_measure: Unit of measure. - :vartype unit_of_measure: str - :ivar included_quantity: Included quality for an offer. - :vartype included_quantity: float - :ivar part_number: Part Number. - :vartype part_number: str - :ivar unit_price: Unit Price. - :vartype unit_price: float - :ivar currency_code: Currency Code. - :vartype currency_code: str - :ivar offer_id: Offer Id. - :vartype offer_id: str - """ - - _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}, - } - - _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().__init__(**kwargs) - self.billing_period_id = None - self.meter_id = None - self.meter_details = None - self.unit_of_measure = None - self.included_quantity = None - self.part_number = None - self.unit_price = None - self.currency_code = None - self.offer_id = None - - -class PriceSheetResult(Resource): - """An pricesheet 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. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar pricesheets: Price sheet. - :vartype pricesheets: list[~azure.mgmt.consumption.models.PriceSheetProperties] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - :ivar download: Pricesheet download details. - :vartype download: ~azure.mgmt.consumption.models.MeterDetails - """ - - _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}, - } - - _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().__init__(**kwargs) - self.pricesheets = None - self.next_link = None - self.download = None - - -class Reseller(_serialization.Model): - """The reseller properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar reseller_id: The reseller property ID. - :vartype reseller_id: str - :ivar reseller_description: The reseller property description. - :vartype reseller_description: str - """ - - _validation = { - "reseller_id": {"readonly": True}, - "reseller_description": {"readonly": True}, - } - - _attribute_map = { - "reseller_id": {"key": "resellerId", "type": "str"}, - "reseller_description": {"key": "resellerDescription", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.reseller_id = None - self.reseller_description = None - - -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. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :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 - order contains reservations. The reservation order specifies the VM size and region for the - reservations. - :vartype reservation_order_id: str - :ivar instance_flexibility_ratio: The instance Flexibility Ratio. - :vartype instance_flexibility_ratio: str - :ivar instance_flexibility_group: The instance Flexibility Group. - :vartype instance_flexibility_group: str - :ivar reservation_id: The reservation ID is the identifier of a reservation within a - reservation order. Each reservation is the grouping for applying the benefit scope and also - specifies the number of instances to which the reservation benefit can be applied to. - :vartype reservation_id: str - :ivar sku_name: This is the ARM Sku name. It can be used to join with the serviceType field in - additional info in usage records. - :vartype sku_name: str - :ivar reserved_hours: This is the total hours reserved for the day. E.g. if reservation for 1 - instance was made on 1 PM, this will be 11 hours for that day and 24 hours from subsequent - days. - :vartype reserved_hours: float - :ivar usage_date: The date on which consumption occurred. - :vartype usage_date: ~datetime.datetime - :ivar used_hours: This is the total hours used by the instance. - :vartype used_hours: float - :ivar instance_id: This identifier is the name of the resource or the fully qualified Resource - ID. - :vartype instance_id: str - :ivar total_reserved_quantity: This is the total count of instances that are reserved for the - reservationId. - :vartype total_reserved_quantity: float - :ivar kind: The reservation kind. - :vartype kind: str - """ - - _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}, - } - - _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().__init__(**kwargs) - self.reservation_order_id = None - self.instance_flexibility_ratio = None - self.instance_flexibility_group = None - self.reservation_id = None - self.sku_name = None - self.reserved_hours = None - self.usage_date = None - self.used_hours = None - self.instance_id = None - self.total_reserved_quantity = None - self.kind = None - - -class ReservationDetailsListResult(_serialization.Model): - """Result of listing reservation details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of reservation details. - :vartype value: list[~azure.mgmt.consumption.models.ReservationDetail] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ReservationDetail]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -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. Includes hardware and software cost. - :vartype on_demand_cost: float - :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: Hardware cost of the resources covered by the reservation. - :vartype reservation_cost: float - :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. 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}, - } - - _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"}, - } - - 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().__init__(**kwargs) - self.on_demand_cost = None - self.overage_cost = None - self.quantity = None - self.reservation_cost = None - self.total_reservation_cost = None - self.reserved_unit_count = reserved_unit_count - self.savings = None - - -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. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar location: Resource Location. - :vartype location: str - :ivar sku: Resource sku. - :vartype sku: str - :ivar currency: An ISO 4217 currency code identifier for the costs and savings. - :vartype currency: str - :ivar resource: Resource specific properties. - :vartype resource: - ~azure.mgmt.consumption.models.ReservationRecommendationDetailsResourceProperties - :ivar resource_group: Resource Group. - :vartype resource_group: str - :ivar savings: Savings information for the recommendation. - :vartype savings: - ~azure.mgmt.consumption.models.ReservationRecommendationDetailsSavingsProperties - :ivar scope: Scope of the reservation, ex: Single or Shared. - :vartype scope: str - :ivar usage: Historical usage details used to calculate the estimated savings. - :vartype usage: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsUsageProperties - """ - - _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}, - } - - _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): - """ - :keyword location: Resource Location. - :paramtype location: str - :keyword sku: Resource sku. - :paramtype sku: str - """ - super().__init__(**kwargs) - self.location = location - self.sku = sku - self.currency = None - self.resource = None - self.resource_group = None - self.savings = None - self.scope = None - self.usage = None - - -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: 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: 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}, - } - - _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"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.applied_scopes = None - self.on_demand_rate = None - self.product = None - self.region = None - self.reservation_rate = None - self.resource_type = None - - -class ReservationRecommendationDetailsSavingsProperties(_serialization.Model): - """Details of the estimated savings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar calculated_savings: List of calculated savings. - :vartype calculated_savings: - list[~azure.mgmt.consumption.models.ReservationRecommendationDetailsCalculatedSavingsProperties] - :ivar look_back_period: Number of days of usage to look back used for computing the - recommendation. - :vartype look_back_period: int - :ivar recommended_quantity: Number of recommended units of the resource. - :vartype recommended_quantity: float - :ivar reservation_order_term: Term period of the reservation, ex: P1Y or P3Y. - :vartype reservation_order_term: str - :ivar savings_type: Type of savings, ex: instance. - :vartype savings_type: str - :ivar unit_of_measure: Measurement unit ex: hour etc. - :vartype unit_of_measure: str - """ - - _validation = { - "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"}, - } - - def __init__( - self, - *, - calculated_savings: Optional[ - List["_models.ReservationRecommendationDetailsCalculatedSavingsProperties"] - ] = None, - **kwargs - ): - """ - :keyword calculated_savings: List of calculated savings. - :paramtype calculated_savings: - list[~azure.mgmt.consumption.models.ReservationRecommendationDetailsCalculatedSavingsProperties] - """ - super().__init__(**kwargs) - self.calculated_savings = calculated_savings - self.look_back_period = None - self.recommended_quantity = None - self.reservation_order_term = None - self.savings_type = None - self.unit_of_measure = None - - -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. - - :ivar first_consumption_date: The first usage date used for looking back for computing the - recommendation. - :vartype first_consumption_date: str - :ivar last_consumption_date: The last usage date used for looking back for computing the - recommendation. - :vartype last_consumption_date: str - :ivar look_back_unit_type: What the usage data values represent ex: virtual machine instance. - :vartype look_back_unit_type: str - :ivar usage_data: The breakdown of historical resource usage. The values are in the order of - usage between the firstConsumptionDate and the lastConsumptionDate. - :vartype usage_data: list[float] - :ivar usage_grain: The grain of the values represented in the usage data ex: hourly. - :vartype usage_grain: str - """ - - _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}, - } - - _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"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.first_consumption_date = None - self.last_consumption_date = None - self.look_back_unit_type = None - self.usage_data = None - self.usage_grain = None - - -class ReservationRecommendationsListResult(_serialization.Model): - """Result of listing reservation recommendations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of reservation recommendations. - :vartype value: list[~azure.mgmt.consumption.models.ReservationRecommendation] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - :ivar previous_link: The link (url) to the previous page of results. - :vartype previous_link: str - """ - - _validation = { - "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"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - self.previous_link = None - - -class ReservationSummariesListResult(_serialization.Model): - """Result of listing reservation summaries. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of reservation summaries. - :vartype value: list[~azure.mgmt.consumption.models.ReservationSummary] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ReservationSummary]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -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. - - :ivar id: The full qualified ARM ID of an event. - :vartype id: str - :ivar name: The ID that uniquely identifies an event. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar etag: The etag for the resource. - :vartype etag: str - :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 - order contains reservations. The reservation order specifies the VM size and region for the - reservations. - :vartype reservation_order_id: str - :ivar reservation_id: The reservation ID is the identifier of a reservation within a - reservation order. Each reservation is the grouping for applying the benefit scope and also - specifies the number of instances to which the reservation benefit can be applied to. - :vartype reservation_id: str - :ivar sku_name: This is the ARM Sku name. It can be used to join with the serviceType field in - additional info in usage records. - :vartype sku_name: str - :ivar reserved_hours: This is the total hours reserved. E.g. if reservation for 1 instance was - made on 1 PM, this will be 11 hours for that day and 24 hours from subsequent days. - :vartype reserved_hours: float - :ivar usage_date: Data corresponding to the utilization record. If the grain of data is - monthly, it will be first day of month. - :vartype usage_date: ~datetime.datetime - :ivar used_hours: Total used hours by the reservation. - :vartype used_hours: float - :ivar min_utilization_percentage: This is the minimum hourly utilization in the usage time (day - or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4 and 5, - utilization was 10%, this field will return 10% for that day. - :vartype min_utilization_percentage: float - :ivar avg_utilization_percentage: This is average utilization for the entire time range. (day - or month depending on the grain). - :vartype avg_utilization_percentage: float - :ivar max_utilization_percentage: This is the maximum hourly utilization in the usage time (day - or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4 and 5, - utilization was 100%, this field will return 100% for that day. - :vartype max_utilization_percentage: float - :ivar kind: The reservation kind. - :vartype kind: str - :ivar purchased_quantity: This is the purchased quantity for the reservationId. - :vartype purchased_quantity: float - :ivar remaining_quantity: This is the remaining quantity for the reservationId. - :vartype remaining_quantity: float - :ivar total_reserved_quantity: This is the total count of instances that are reserved for the - reservationId. - :vartype total_reserved_quantity: float - :ivar used_quantity: This is the used quantity for the reservationId. - :vartype used_quantity: float - :ivar utilized_percentage: This is the utilized percentage for the reservation Id. - :vartype utilized_percentage: float - """ - - _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}, - } - - _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().__init__(**kwargs) - self.reservation_order_id = None - self.reservation_id = None - self.sku_name = None - self.reserved_hours = None - self.usage_date = None - self.used_hours = None - self.min_utilization_percentage = None - self.avg_utilization_percentage = None - self.max_utilization_percentage = None - self.kind = None - self.purchased_quantity = None - self.remaining_quantity = None - self.total_reserved_quantity = None - self.used_quantity = None - self.utilized_percentage = None - - -class ReservationTransactionsListResult(_serialization.Model): - """Result of listing reservation recommendations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of reservation recommendations. - :vartype value: list[~azure.mgmt.consumption.models.ReservationTransaction] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ReservationTransaction]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - - -class SkuProperty(_serialization.Model): - """The Sku property. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of sku property. - :vartype name: str - :ivar value: The value of sku property. - :vartype value: str - """ - - _validation = { - "name": {"readonly": True}, - "value": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "value": {"key": "value", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.name = None - self.value = None - - -class Tag(_serialization.Model): - """The tag resource. - - :ivar key: Tag key. - :vartype key: str - :ivar value: Tag values. - :vartype value: list[str] - """ - - _attribute_map = { - "key": {"key": "key", "type": "str"}, - "value": {"key": "value", "type": "[str]"}, - } - - 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().__init__(**kwargs) - self.key = key - self.value = value - - -class TagsResult(ProxyResource): - """A resource listing all tags. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar 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 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 - :ivar previous_link: The link (url) to the previous page of results. - :vartype previous_link: str - """ - - _validation = { - "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"}, - } - - 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 list of Tag. - :paramtype tags: list[~azure.mgmt.consumption.models.Tag] - """ - super().__init__(e_tag=e_tag, **kwargs) - self.tags = tags - self.next_link = None - self.previous_link = None - - -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. - - :ivar value: The list of usage details. - :vartype value: list[~azure.mgmt.consumption.models.UsageDetail] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[UsageDetail]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - 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 f7dd32510333..ea765788358a 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 @@ -1,14 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): 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 33de5eb645bc..ef22c6aa0d68 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 @@ -2,36 +2,45 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._usage_details_operations import UsageDetailsOperations -from ._marketplaces_operations import MarketplacesOperations -from ._budgets_operations import BudgetsOperations -from ._tags_operations import TagsOperations -from ._charges_operations import ChargesOperations -from ._balances_operations import BalancesOperations -from ._reservations_summaries_operations import ReservationsSummariesOperations -from ._reservations_details_operations import ReservationsDetailsOperations -from ._reservation_recommendations_operations import ReservationRecommendationsOperations -from ._reservation_recommendation_details_operations import ReservationRecommendationDetailsOperations -from ._reservation_transactions_operations import ReservationTransactionsOperations -from ._price_sheet_operations import PriceSheetOperations -from ._operations import Operations -from ._aggregated_cost_operations import AggregatedCostOperations -from ._events_operations import EventsOperations -from ._lots_operations import LotsOperations -from ._credits_operations import CreditsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._operations import PriceSheetOperations # type: ignore +from ._operations import BudgetsOperations # type: ignore +from ._operations import CreditsOperations # type: ignore +from ._operations import UsageDetailsOperations # type: ignore +from ._operations import MarketplacesOperations # type: ignore +from ._operations import TagsOperations # type: ignore +from ._operations import ChargesOperations # type: ignore +from ._operations import BalancesOperations # type: ignore +from ._operations import ReservationsSummariesOperations # type: ignore +from ._operations import ReservationsDetailsOperations # type: ignore +from ._operations import ReservationRecommendationsOperations # type: ignore +from ._operations import ReservationRecommendationDetailsOperations # type: ignore +from ._operations import ReservationTransactionsOperations # type: ignore +from ._operations import AggregatedCostOperations # type: ignore +from ._operations import EventsOperations # type: ignore +from ._operations import LotsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ + "Operations", + "PriceSheetOperations", + "BudgetsOperations", + "CreditsOperations", "UsageDetailsOperations", "MarketplacesOperations", - "BudgetsOperations", "TagsOperations", "ChargesOperations", "BalancesOperations", @@ -40,12 +49,9 @@ "ReservationRecommendationsOperations", "ReservationRecommendationDetailsOperations", "ReservationTransactionsOperations", - "PriceSheetOperations", - "Operations", "AggregatedCostOperations", "EventsOperations", "LotsOperations", - "CreditsOperations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _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 deleted file mode 100644 index 9c2f27dc3073..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_aggregated_cost_operations.py +++ /dev/null @@ -1,253 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -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 -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - 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 -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), - "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class AggregatedCostOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`aggregated_cost` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get_by_management_group( - 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. 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 - does not currently support 'ne', 'or', or 'not'. 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: ManagementGroupAggregatedCostResult or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - filter=filter, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } - - @distributed_trace - def get_for_billing_period_by_management_group( - 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. Required. - :type management_group_id: str - :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) - :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index 2120804fedc2..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_balances_operations.py +++ /dev/null @@ -1,241 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -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: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_for_billing_period_by_billing_account_request( - 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: 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class BalancesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`balances` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get_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. 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) - :rtype: ~azure.mgmt.consumption.models.Balance - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } - - @distributed_trace - def get_for_billing_period_by_billing_account( - 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. Required. - :type billing_account_id: str - :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) - :rtype: ~azure.mgmt.consumption.models.Balance - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index f8731081cab6..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_budgets_operations.py +++ /dev/null @@ -1,581 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_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: 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), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(scope: str, budget_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request(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: 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"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request(scope: str, budget_name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class BudgetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`budgets` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def 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 - '/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 - :keyword callable cls: A custom type or function that will be passed the direct response - :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: 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, - 304: ResourceNotModifiedError, - } - 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets"} - - @distributed_trace - 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 - '/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 - :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, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("Budget", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/budgets/{budgetName}"} - - @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 - 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: ~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) - :rtype: ~azure.mgmt.consumption.models.Budget - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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) - - 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, - budget_name=budget_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.create_or_update.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize("Budget", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("Budget", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # 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 - ) -> None: - """The operation to delete a budget. - - :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 - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - 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 deleted file mode 100644 index e471dfe96028..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_charges_operations.py +++ /dev/null @@ -1,197 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -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, - *, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - filter: Optional[str] = None, - apply: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _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") - if end_date is not None: - _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if apply is not None: - _params["$apply"] = _SERIALIZER.query("apply", apply, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ChargesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`charges` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - scope: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - filter: Optional[str] = None, - apply: Optional[str] = None, - **kwargs: Any - ) -> _models.ChargesListResult: - """Lists the charges based for the defined scope. - - :param scope: The scope associated with charges operations. This includes - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' - for Department scope, and - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' - for EnrollmentAccount scope. For department and enrollment accounts, you can also add billing - period to the scope using '/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. - For e.g. to specify billing period at department scope use - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. - Also, Modern Commerce Account scopes are - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. Required. - :type scope: str - :param start_date: Start date. Default value is None. - :type start_date: str - :param end_date: End date. Default value is None. - :type end_date: str - :param filter: May be used to filter charges by properties/usageEnd (Utc time), - properties/usageStart (Utc time). The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. - It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where - key and value is separated by a colon (:). Default value is None. - :type filter: str - :param apply: May be used to group charges for billingAccount scope by - properties/billingProfileId, properties/invoiceSectionId, properties/customerId (specific for - Partner Led), or for billingProfile scope by properties/invoiceSectionId. Default value is - 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) - :rtype: ~azure.mgmt.consumption.models.ChargesListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - start_date=start_date, - end_date=end_date, - filter=filter, - apply=apply, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChargesListResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - 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 deleted file mode 100644 index 530dbf701b32..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_credits_operations.py +++ /dev/null @@ -1,151 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -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: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class CreditsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`credits` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, 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. Required. - :type billing_account_id: str - :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 None or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.CreditSummary or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index a9f78867dcfb..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_events_operations.py +++ /dev/null @@ -1,317 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_billing_profile_request( - billing_account_id: str, billing_profile_id: str, *, start_date: str, end_date: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), - } - - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - 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 -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class EventsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`events` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_billing_profile( - 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. Required. - :type billing_account_id: str - :param billing_profile_id: Azure Billing Profile ID. Required. - :type billing_profile_id: str - :param start_date: Start date. Required. - :type start_date: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - start_date=start_date, - end_date=end_date, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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.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. 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'. - 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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 deleted file mode 100644 index cd94ed0583b9..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_lots_operations.py +++ /dev/null @@ -1,439 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_billing_profile_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: 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_by_billing_account_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: 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_by_customer_request( - 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: 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class LotsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`lots` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_billing_profile( - 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. Required. - :type billing_account_id: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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.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. 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 - 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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.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. Required. - :type billing_account_id: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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 deleted file mode 100644 index 36cc085b75d9..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_marketplaces_operations.py +++ /dev/null @@ -1,217 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - scope: str, - *, - filter: Optional[str] = None, - top: Optional[int] = None, - skiptoken: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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), - } - - _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") - if top is not None: - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class MarketplacesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`marketplaces` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - scope: str, - filter: Optional[str] = None, - top: Optional[int] = None, - skiptoken: Optional[str] = None, - **kwargs: Any - ) -> 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. - - :param scope: The scope associated with marketplace operations. This includes - '/subscriptions/{subscriptionId}/' for subscription scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, - '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, - '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount - scope and '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management - Group scope. For subscription, billing account, department, enrollment account and - ManagementGroup, you can also add billing period to the scope using - '/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 - properties/instanceId. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not - currently support 'ne', 'or', or 'not'. Default value is None. - :type filter: str - :param top: May be used to limit the number of results to the most recent N marketplaces. - Default value is None. - :type top: int - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - 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 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: 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, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_request( - scope=scope, - filter=filter, - top=top, - skiptoken=skiptoken, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.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 5dd6eb4d602c..68d4c0719183 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 @@ -1,55 +1,61 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python 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 collections.abc import MutableMapping +import decimal +from io import IOBase +import json +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request +from .._configuration import ConsumptionManagementClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Deserializer, Serializer -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request(**kwargs: Any) -> HttpRequest: +def build_operations_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-10-01"] = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Consumption/operations") + _url = "/providers/Microsoft.Consumption/operations" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -60,6 +66,967 @@ def build_list_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) +def build_price_sheet_get_by_billing_period_request( # pylint: disable=name-too-long + billing_period_name: str, + subscription_id: str, + *, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/default" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_price_sheet_get_request( + subscription_id: str, + *, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_price_sheet_download_by_billing_account_period_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/pricesheets/download" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_budgets_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _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"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_budgets_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 {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _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"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_budgets_delete_request(scope: str, budget_name: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + # Construct URL + _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"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_budgets_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{scope}/providers/Microsoft.Consumption/budgets" + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_credits_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/credits/balanceSummary" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_usage_details_list_request( + scope: str, + *, + expand: Optional[str] = None, + filter: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{scope}/providers/Microsoft.Consumption/usageDetails" + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if metric is not None: + _params["metric"] = _SERIALIZER.query("metric", metric, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_marketplaces_list_request( + scope: str, + *, + filter: Optional[str] = None, + top: Optional[int] = None, + skiptoken: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{scope}/providers/Microsoft.Consumption/marketplaces" + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_tags_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{scope}/providers/Microsoft.Consumption/tags" + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_charges_list_request( + scope: str, + *, + start_date: Optional[str] = None, + end_date: Optional[str] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{scope}/providers/Microsoft.Consumption/charges" + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + if end_date is not None: + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_balances_get_by_billing_account_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/balances" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_balances_get_for_billing_period_by_billing_account_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/balances" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_summaries_list_by_reservation_order_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries" + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["grain"] = _SERIALIZER.query("grain", grain, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_summaries_list_by_reservation_order_and_reservation_request( # pylint: disable=name-too-long + reservation_order_id: str, + reservation_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries" + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["grain"] = _SERIALIZER.query("grain", grain, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_summaries_list_request( # pylint: disable=name-too-long + resource_scope: str, + *, + 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 +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceScope}/providers/Microsoft.Consumption/reservationSummaries" + path_format_arguments = { + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["grain"] = _SERIALIZER.query("grain", grain, "str") + if start_date is not None: + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") + if end_date is not None: + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if reservation_id is not None: + _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") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_details_list_by_reservation_order_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationDetails" + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_details_list_by_reservation_order_and_reservation_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails" + path_format_arguments = { + "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), + "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_details_list_request( + resource_scope: str, + *, + 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 +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceScope}/providers/Microsoft.Consumption/reservationDetails" + path_format_arguments = { + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _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") + if end_date is not None: + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if reservation_id is not None: + _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") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_recommendations_list_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendations" + path_format_arguments = { + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_recommendation_details_get_request( # pylint: disable=name-too-long + resource_scope: str, + *, + scope: Union[str, _models.Scope], + region: str, + term: Union[str, _models.Term], + look_back_period: Union[str, _models.LookBackPeriod], + product: 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceScope}/providers/Microsoft.Consumption/reservationRecommendationDetails" + path_format_arguments = { + "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), + } + + _url: str = _url.format(**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") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_transactions_list_request( # pylint: disable=name-too-long + billing_account_id: str, + *, + filter: Optional[str] = None, + use_markup_if_partner: Optional[bool] = None, + preview_markup_percentage: Optional[decimal.Decimal] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/reservationTransactions" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if use_markup_if_partner is not None: + _params["useMarkupIfPartner"] = _SERIALIZER.query("use_markup_if_partner", use_markup_if_partner, "bool") + if preview_markup_percentage is not None: + _params["previewMarkupPercentage"] = _SERIALIZER.query( + "preview_markup_percentage", preview_markup_percentage, "decimal" + ) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_transactions_list_by_billing_profile_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/reservationTransactions" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_aggregated_cost_get_by_management_group_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Consumption/aggregatedcost" + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_aggregated_cost_get_for_billing_period_by_management_group_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}/providers/Microsoft.Consumption/aggregatedCost" + path_format_arguments = { + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_events_list_by_billing_profile_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/events" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), + } + + _url: str = _url.format(**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") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_events_list_by_billing_account_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/events" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_lots_list_by_billing_profile_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Consumption/lots" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_lots_list_by_billing_account_request( # pylint: disable=name-too-long + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Consumption/lots" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_lots_list_by_customer_request( + 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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}/providers/Microsoft.Consumption/lots" + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + class Operations: """ .. warning:: @@ -67,36 +1034,3375 @@ class Operations: Instead, you should access the following operations through :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`operations` attribute. + :attr:`operations` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of Operation + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Operation], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class PriceSheetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`price_sheet` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_by_billing_period( + self, + billing_period_name: str, + *, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> _models.PriceSheetResult: + """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. Required. + :type billing_period_name: str + :keyword 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. + :paramtype expand: str + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :keyword top: May be used to limit the number of results to the top N results. Default value is + None. + :paramtype top: int + :return: PriceSheetResult. The PriceSheetResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.PriceSheetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) + + _request = build_price_sheet_get_by_billing_period_request( + billing_period_name=billing_period_name, + subscription_id=self._config.subscription_id, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PriceSheetResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get( + 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. + + :keyword 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. + :paramtype expand: str + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :keyword top: May be used to limit the number of results to the top N results. Default value is + None. + :paramtype top: int + :return: PriceSheetResult. The PriceSheetResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.PriceSheetResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PriceSheetResult] = kwargs.pop("cls", None) + + _request = build_price_sheet_get_request( + subscription_id=self._config.subscription_id, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PriceSheetResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _download_by_billing_account_period_initial( # pylint: disable=name-too-long + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_price_sheet_download_by_billing_account_period_request( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_download_by_billing_account_period( + self, billing_account_id: str, billing_period_name: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatus]: + """Generates the pricesheet for the provided billing period asynchronously based on the enrollment + id. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: An instance of LROPoller that returns OperationStatus. The OperationStatus is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.consumption.models.OperationStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._download_by_billing_account_period_initial( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response = pipeline_response.http_response + deserialized = _deserialize(_models.OperationStatus, response.json()) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.OperationStatus].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.OperationStatus]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class BudgetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`budgets` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget: + """Gets the budget for the scope by budget name. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) + + _request = build_budgets_get_request( + scope=scope, + budget_name=budget_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Budget, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @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 + 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 fully qualified Azure Resource manager identifier of the resource. 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: ~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 + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, scope: str, budget_name: str, parameters: JSON, *, 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 fully qualified Azure Resource manager identifier of the resource. 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: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + scope: str, + budget_name: str, + parameters: IO[bytes], + *, + 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 fully qualified Azure Resource manager identifier of the resource. 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[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Budget. The Budget is compatible with MutableMapping + :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, JSON, IO[bytes]], **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 fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :param parameters: Parameters supplied to the Create Budget operation. Is one of the following + types: Budget, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.consumption.models.Budget or JSON or IO[bytes] + :return: Budget. The Budget is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Budget + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Budget] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_budgets_create_or_update_request( + scope=scope, + budget_name=budget_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Budget, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, budget_name: str, **kwargs: Any + ) -> None: + """The operation to delete a budget. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :param budget_name: Budget Name. Required. + :type budget_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_budgets_delete_request( + scope=scope, + budget_name=budget_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list(self, scope: str, **kwargs: Any) -> ItemPaged["_models.Budget"]: + """Lists all budgets for the defined scope. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :return: An iterator like instance of Budget + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Budget] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Budget]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_budgets_list_request( + scope=scope, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Budget], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class CreditsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`credits` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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]: + """The credit summary by billingAccountId and billingProfileId. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :return: CreditSummary or None. The CreditSummary is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.CreditSummary or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Optional[_models.CreditSummary]] = kwargs.pop("cls", None) + + _request = build_credits_get_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CreditSummary, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class UsageDetailsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`usage_details` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + scope: str, + *, + expand: Optional[str] = None, + filter: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + metric: Optional[Union[str, _models.Metrictype]] = None, + **kwargs: Any + ) -> ItemPaged["_models.UsageDetail"]: + """Lists the usage details for the defined scope. Usage details are available via this API only + for May 1, 2014 or later. + + **Note:Microsoft will be retiring the Consumption Usage Details API at some point in the + future. We do not recommend that you take a new dependency on this API. Please use the Cost + Details API instead. We will notify customers once a date for retirement has been + determined.For Learn more,see [Generate Cost Details Report - Create + Operation](https://learn.microsoft.com/en-us/rest/api/cost-management/generate-cost-details-report/create-operation?tabs=HTTP)**. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :keyword 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 + details. Default value is None. + :paramtype expand: str + :keyword filter: May be used to filter usageDetails by properties/resourceGroup, + properties/resourceName, properties/resourceId, properties/chargeType, + properties/reservationId, properties/publisherType or tags. The filter supports 'eq', 'lt', + 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is + a key value pair string where key and value is separated by a colon (:). PublisherType Filter + accepts two values azure and marketplace and it is currently supported for Web Direct Offer + Type. Default value is None. + :paramtype filter: str + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :keyword top: May be used to limit the number of results to the most recent N usageDetails. + Default value is None. + :paramtype top: int + :keyword metric: Allows to select different type of cost/usage records. Known values are: + "actualcost", "amortizedcost", and "usage". Default value is None. + :paramtype metric: str or ~azure.mgmt.consumption.models.Metrictype + :return: An iterator like instance of UsageDetail + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.UsageDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.UsageDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_usage_details_list_request( + scope=scope, + expand=expand, + filter=filter, + skiptoken=skiptoken, + top=top, + metric=metric, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.UsageDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class MarketplacesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`marketplaces` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + scope: str, + *, + filter: Optional[str] = None, + top: Optional[int] = None, + skiptoken: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_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. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :keyword filter: May be used to filter marketplaces by properties/usageEnd (Utc time), + properties/usageStart (Utc time), properties/resourceGroup, properties/instanceName or + properties/instanceId. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not + currently support 'ne', 'or', or 'not'. Default value is None. + :paramtype filter: str + :keyword top: May be used to limit the number of results to the most recent N marketplaces. + Default value is None. + :paramtype top: int + :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result. + If a previous response contains a nextLink element, the value of the nextLink element will + include a skiptoken parameter that specifies a starting point to use for subsequent calls. + Default value is None. + :paramtype skiptoken: str + :return: An iterator like instance of Marketplace + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Marketplace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Marketplace]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_marketplaces_list_request( + scope=scope, + filter=filter, + top=top, + skiptoken=skiptoken, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Marketplace], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class TagsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`tags` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, scope: str, **kwargs: Any) -> Optional[_models.TagsResult]: + """Get all available tag keys for the defined scope. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :return: TagsResult or None. The TagsResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.TagsResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Optional[_models.TagsResult]] = kwargs.pop("cls", None) + + _request = build_tags_get_request( + scope=scope, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.TagsResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ChargesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`charges` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + scope: str, + *, + start_date: Optional[str] = None, + end_date: Optional[str] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + **kwargs: Any + ) -> _models.ChargesListResult: + """Lists the charges based for the defined scope. + + :param scope: The fully qualified Azure Resource manager identifier of the resource. Required. + :type scope: str + :keyword start_date: Start date. Default value is None. + :paramtype start_date: str + :keyword end_date: End date. Default value is None. + :paramtype end_date: str + :keyword filter: May be used to filter charges by properties/usageEnd (Utc time), + properties/usageStart (Utc time). The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. + It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where + key and value is separated by a colon (:). Default value is None. + :paramtype filter: str + :keyword apply: May be used to group charges for billingAccount scope by + properties/billingProfileId, properties/invoiceSectionId, properties/customerId (specific for + Partner Led), or for billingProfile scope by properties/invoiceSectionId. Default value is + None. + :paramtype apply: str + :return: ChargesListResult. The ChargesListResult is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ChargesListResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ChargesListResult] = kwargs.pop("cls", None) + + _request = build_charges_list_request( + scope=scope, + start_date=start_date, + end_date=end_date, + filter=filter, + apply=apply, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ChargesListResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class BalancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`balances` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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: + """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. Required. + :type billing_account_id: str + :return: Balance. The Balance is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Balance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) + + _request = build_balances_get_by_billing_account_request( + billing_account_id=billing_account_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Balance, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_for_billing_period_by_billing_account( # pylint: disable=name-too-long + 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. Required. + :type billing_account_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: Balance. The Balance is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.Balance + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Balance] = kwargs.pop("cls", None) + + _request = build_balances_get_for_billing_period_by_billing_account_request( + billing_account_id=billing_account_id, + billing_period_name=billing_period_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Balance, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ReservationsSummariesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`reservations_summaries` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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], + filter: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.ReservationSummary"]: + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 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. Required. + :type reservation_order_id: str + :keyword grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. + :paramtype grain: str or ~azure.mgmt.consumption.models.Datagrain + :keyword 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. + :paramtype filter: str + :return: An iterator like instance of ReservationSummary + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_summaries_list_by_reservation_order_request( + reservation_order_id=reservation_order_id, + grain=grain, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long + self, + reservation_order_id: str, + reservation_id: str, + *, + grain: Union[str, _models.Datagrain], + filter: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.ReservationSummary"]: + """Lists the reservations summaries for daily or monthly grain. Note: ARM has a payload size limit + of 12MB, so currently callers get 400 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. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation. Required. + :type reservation_id: str + :keyword grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. + :paramtype grain: str or ~azure.mgmt.consumption.models.Datagrain + :keyword 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. + :paramtype filter: str + :return: An iterator like instance of ReservationSummary + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_summaries_list_by_reservation_order_and_reservation_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + grain=grain, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, + resource_scope: str, + *, + 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 + ) -> ItemPaged["_models.ReservationSummary"]: + """Lists the reservations summaries for the defined scope daily or monthly grain. Note: ARM has a + payload size limit of 12MB, so currently callers get 400 when the response size exceeds the ARM + limit. In such cases, API call should be made with smaller date ranges. + + :param resource_scope: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_scope: str + :keyword grain: Can be daily or monthly. Known values are: "daily" and "monthly". Required. + :paramtype grain: str or ~azure.mgmt.consumption.models.Datagrain + :keyword start_date: Start date. Only applicable when querying with billing profile. Default + value is None. + :paramtype start_date: str + :keyword end_date: End date. Only applicable when querying with billing profile. Default value + is None. + :paramtype end_date: str + :keyword filter: Required only for daily grain. The properties/UsageDate for start date and end + date. The filter supports 'le' and 'ge'. Not applicable when querying with billing profile. + Default value is None. + :paramtype filter: str + :keyword reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also + provided. Filter to a specific reservation. Default value is None. + :paramtype reservation_id: str + :keyword reservation_order_id: Reservation Order Id GUID. Required if reservationId is + provided. Filter to a specific reservation order. Default value is None. + :paramtype reservation_order_id: str + :return: An iterator like instance of ReservationSummary + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_summaries_list_request( + resource_scope=resource_scope, + grain=grain, + start_date=start_date, + end_date=end_date, + filter=filter, + reservation_id=reservation_id, + reservation_order_id=reservation_order_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class ReservationsDetailsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`reservations_details` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> ItemPaged["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :keyword filter: Filter reservation details by date range. The properties/UsageDate for start + date and end date. The filter supports 'le' and 'ge'. Required. + :paramtype filter: str + :return: An iterator like instance of ReservationDetail + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_details_list_by_reservation_order_request( + reservation_order_id=reservation_order_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_reservation_order_and_reservation( # pylint: disable=name-too-long + self, reservation_order_id: str, reservation_id: str, *, filter: str, **kwargs: Any + ) -> ItemPaged["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation. Required. + :type reservation_id: str + :keyword filter: Filter reservation details by date range. The properties/UsageDate for start + date and end date. The filter supports 'le' and 'ge'. Required. + :paramtype filter: str + :return: An iterator like instance of ReservationDetail + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_details_list_by_reservation_order_and_reservation_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list( + self, + resource_scope: str, + *, + 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 + ) -> ItemPaged["_models.ReservationDetail"]: + """Lists the reservations details for provided date range. Note: ARM has a payload size limit of + 12MB, so currently callers get 400 when the response size exceeds the ARM limit. If the data + size is too large, customers may also get 504 as the API timed out preparing the data. In such + cases, API call should be made with smaller date ranges or a call to Generate Reservation + Details Report API should be made as it is asynchronous and will not run into response size + time outs. + + :param resource_scope: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_scope: str + :keyword start_date: Start date. Only applicable when querying with billing profile. Default + value is None. + :paramtype start_date: str + :keyword end_date: End date. Only applicable when querying with billing profile. Default value + is None. + :paramtype end_date: str + :keyword filter: Filter reservation details by date range. The properties/UsageDate for start + date and end date. The filter supports 'le' and 'ge'. Not applicable when querying with + billing profile. Default value is None. + :paramtype filter: str + :keyword reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also + provided. Filter to a specific reservation. Default value is None. + :paramtype reservation_id: str + :keyword reservation_order_id: Reservation Order Id GUID. Required if reservationId is + provided. Filter to a specific reservation order. Default value is None. + :paramtype reservation_order_id: str + :return: An iterator like instance of ReservationDetail + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationDetail] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationDetail]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservations_details_list_request( + resource_scope=resource_scope, + start_date=start_date, + end_date=end_date, + filter=filter, + reservation_id=reservation_id, + reservation_order_id=reservation_order_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationDetail], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class ReservationRecommendationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`reservation_recommendations` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> ItemPaged["_models.ReservationRecommendation"]: + """List of recommendations for purchasing reserved instances. + + :param resource_scope: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_scope: str + :keyword filter: May be used to filter reservationRecommendations by: properties/scope with + allowed values ['Single', 'Shared'] and default value 'Single'; properties/resourceType with + allowed values ['VirtualMachines', 'SQLDatabases', 'PostgreSQL', 'ManagedDisk', 'MySQL', + 'RedHat', 'MariaDB', 'RedisCache', 'CosmosDB', 'SqlDataWarehouse', 'SUSELinux', 'AppService', + 'BlockBlob', 'AzureDataExplorer', 'VMwareCloudSimple'] and default value 'VirtualMachines'; and + properties/lookBackPeriod with allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and + default value 'Last7Days'. Default value is None. + :paramtype filter: str + :return: An iterator like instance of ReservationRecommendation + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationRecommendation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationRecommendation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservation_recommendations_list_request( + resource_scope=resource_scope, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationRecommendation], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class ReservationRecommendationDetailsOperations: # pylint: disable=name-too-long + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`reservation_recommendation_details` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, + resource_scope: str, + *, + scope: Union[str, _models.Scope], + region: str, + term: Union[str, _models.Term], + look_back_period: Union[str, _models.LookBackPeriod], + product: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Optional[_models.ReservationRecommendationDetailsModel]: + """Details of a reservation recommendation for what-if analysis of reserved instances. + + :param resource_scope: The scope associated with reservation recommendation details operations. + This includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/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. Required. + :type resource_scope: str + :keyword scope: Scope of the reservation. Known values are: "Single" and "Shared". Required. + :paramtype scope: str or ~azure.mgmt.consumption.models.Scope + :keyword region: Used to select the region the recommendation should be generated for. + Required. + :paramtype region: str + :keyword term: Specify length of reservation recommendation term. Known values are: "P1M", + "P1Y", and "P3Y". Required. + :paramtype term: str or ~azure.mgmt.consumption.models.Term + :keyword look_back_period: Filter the time period on which reservation recommendation results + are based. Known values are: "Last7Days", "Last30Days", and "Last60Days". Required. + :paramtype look_back_period: str or ~azure.mgmt.consumption.models.LookBackPeriod + :keyword 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. + :paramtype product: str + :keyword filter: Used to filter reservation recommendation details by: + properties/subscriptionId can be specified for billing account and billing profile paths. + Default value is None. + :paramtype filter: str + :return: ReservationRecommendationDetailsModel or None. The + ReservationRecommendationDetailsModel is compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Optional[_models.ReservationRecommendationDetailsModel]] = kwargs.pop("cls", None) + + _request = build_reservation_recommendation_details_get_request( + resource_scope=resource_scope, + scope=scope, + region=region, + term=term, + look_back_period=look_back_period, + product=product, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.HighCasedErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ReservationRecommendationDetailsModel, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ReservationTransactionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`reservation_transactions` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + billing_account_id: str, + *, + filter: Optional[str] = None, + use_markup_if_partner: Optional[bool] = None, + preview_markup_percentage: Optional[decimal.Decimal] = None, + **kwargs: Any + ) -> ItemPaged["_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. Note: ARM has a payload size limit of 12MB, so currently callers get 400 when the + response size exceeds the ARM limit. In such cases, API call should be made with smaller date + ranges. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :keyword filter: Filter reservation transactions by date range. The properties/EventDate for + 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. + :paramtype filter: str + :keyword use_markup_if_partner: Applies mark up to the transactions if the caller is a partner. + Default value is None. + :paramtype use_markup_if_partner: bool + :keyword preview_markup_percentage: Preview markup percentage to be applied. Default value is + None. + :paramtype preview_markup_percentage: ~decimal.Decimal + :return: An iterator like instance of ReservationTransaction + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ReservationTransaction]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservation_transactions_list_request( + billing_account_id=billing_account_id, + filter=filter, + use_markup_if_partner=use_markup_if_partner, + preview_markup_percentage=preview_markup_percentage, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ReservationTransaction], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_billing_profile( + self, billing_account_id: str, billing_profile_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_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. Note: ARM + has a payload size limit of 12MB, so currently callers get 400 when the response size exceeds + the ARM limit. In such cases, API call should be made with smaller date ranges. + + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :keyword filter: Filter reservation transactions by date range. The properties/EventDate for + 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. + :paramtype filter: str + :return: An iterator like instance of ModernReservationTransaction + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.ModernReservationTransaction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ModernReservationTransaction]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_reservation_transactions_list_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ModernReservationTransaction], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class AggregatedCostOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`aggregated_cost` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> _models.ManagementGroupAggregatedCostResult: + """Provides the aggregate cost of a management group and all child management groups by current + billing period. + + :param management_group_id: Order Id of the reservation. Required. + :type management_group_id: str + :keyword 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. + :paramtype filter: str + :return: ManagementGroupAggregatedCostResult. The ManagementGroupAggregatedCostResult is + compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) + + _request = build_aggregated_cost_get_by_management_group_request( + management_group_id=management_group_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupAggregatedCostResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_for_billing_period_by_management_group( # pylint: disable=name-too-long + 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: Order Id of the reservation. Required. + :type management_group_id: str + :param billing_period_name: Billing Period Name. Required. + :type billing_period_name: str + :return: ManagementGroupAggregatedCostResult. The ManagementGroupAggregatedCostResult is + compatible with MutableMapping + :rtype: ~azure.mgmt.consumption.models.ManagementGroupAggregatedCostResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ManagementGroupAggregatedCostResult] = kwargs.pop("cls", None) + + _request = build_aggregated_cost_get_for_billing_period_by_management_group_request( + management_group_id=management_group_id, + billing_period_name=billing_period_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ManagementGroupAggregatedCostResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class EventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`events` attribute. """ - models = _models - - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") + ) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: - """Lists all of the available consumption REST API operations. + def list_by_billing_profile( + self, billing_account_id: str, billing_profile_id: str, *, start_date: str, end_date: str, **kwargs: Any + ) -> ItemPaged["_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. - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.Operation] + :param billing_account_id: BillingAccount ID. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :keyword start_date: Start date. Required. + :paramtype start_date: str + :keyword end_date: End date. Required. + :paramtype end_date: str + :return: An iterator like instance of EventSummary + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.EventSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EventSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_events_list_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + start_date=start_date, + end_date=end_date, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.EventSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_billing_account( + self, billing_account_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_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. Required. + :type billing_account_id: str + :keyword 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'. + Tag filter is a key value pair string where key and value is separated by a colon (:). Default + value is None. + :paramtype filter: str + :return: An iterator like instance of EventSummary + :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 {}) + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EventSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_events_list_by_billing_account_request( + billing_account_id=billing_account_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.EventSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class LotsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s + :attr:`lots` attribute. + """ - api_version: Literal["2021-10-01"] = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: ConsumptionManagementClientConfiguration = ( + input_args.pop(0) if input_args else kwargs.pop("config") ) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = 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 + ) -> ItemPaged["_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. Required. + :type billing_account_id: str + :param billing_profile_id: Azure Billing Profile ID. Required. + :type billing_profile_id: str + :return: An iterator like instance of LotSummary + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.LotSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_lots_list_by_billing_profile_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.LotSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_billing_account( + self, billing_account_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_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. Required. + :type billing_account_id: str + :keyword 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 filter is a key value pair string where key and value is separated by a colon (:). Default + value is None. + :paramtype filter: str + :return: An iterator like instance of LotSummary + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.LotSummary]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -107,14 +4413,19 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( - api_version=api_version, - template_url=self.list.metadata["url"], + _request = build_lots_list_by_billing_account_request( + billing_account_id=billing_account_id, + filter=filter, + api_version=self._config.api_version, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -126,36 +4437,154 @@ def prepare_request(next_link=None): } ) _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 = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.LotSummary], + deserialized.get("value", []), + ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("nextLink") or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/providers/Microsoft.Consumption/operations"} + @distributed_trace + def list_by_customer( + self, billing_account_id: str, customer_id: str, *, filter: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_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. Required. + :type billing_account_id: str + :param customer_id: Customer ID. Required. + :type customer_id: str + :keyword 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. + :paramtype filter: str + :return: An iterator like instance of LotSummary + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.consumption.models.LotSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.LotSummary]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_lots_list_by_customer_request( + billing_account_id=billing_account_id, + customer_id=customer_id, + filter=filter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.LotSummary], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) 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 f7dd32510333..ea765788358a 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 @@ -1,14 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# 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. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): 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 deleted file mode 100644 index 971a66821334..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_price_sheet_operations.py +++ /dev/null @@ -1,294 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -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, - *, - expand: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _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") - if skiptoken is not None: - _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - _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_by_billing_period_request( - billing_period_name: str, - subscription_id: str, - *, - expand: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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 - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), - } - - _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") - if skiptoken is not None: - _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PriceSheetOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`price_sheet` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get( - self, 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. - - :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. - :type expand: str - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - value is None. - :type skiptoken: str - :param top: May be used to limit the number of results to the top N results. Default value is - 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) - :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - expand=expand, - skiptoken=skiptoken, - top=top, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PriceSheetResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Consumption/pricesheets/default"} - - @distributed_trace - def get_by_billing_period( - self, - billing_period_name: str, - expand: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> _models.PriceSheetResult: - """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. 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. - :type expand: str - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - value is None. - :type skiptoken: str - :param top: May be used to limit the number of results to the top N results. Default value is - 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) - :rtype: ~azure.mgmt.consumption.models.PriceSheetResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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( - billing_period_name=billing_period_name, - subscription_id=self._config.subscription_id, - expand=expand, - skiptoken=skiptoken, - top=top, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("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" - } 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 deleted file mode 100644 index 7e44d960f078..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendation_details_operations.py +++ /dev/null @@ -1,191 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request( - resource_scope: str, - *, - scope: Union[str, _models.Scope], - region: str, - 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: 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" - ) - path_format_arguments = { - "resourceScope": _SERIALIZER.url("resource_scope", resource_scope, "str", skip_quote=True), - } - - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReservationRecommendationDetailsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`reservation_recommendation_details` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get( - self, - resource_scope: str, - scope: Union[str, _models.Scope], - region: str, - term: Union[str, _models.Term], - look_back_period: Union[str, _models.LookBackPeriod], - product: str, - **kwargs: Any - ) -> Optional[_models.ReservationRecommendationDetailsModel]: - """Details of a reservation recommendation for what-if analysis of reserved instances. - - :param resource_scope: The scope associated with reservation recommendation details operations. - This includes '/subscriptions/{subscriptionId}/' for subscription scope, - '/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. Required. - :type resource_scope: str - :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. Required. - :type region: str - :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. 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 None or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.ReservationRecommendationDetailsModel or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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, - scope=scope, - region=region, - term=term, - look_back_period=look_back_period, - product=product, - 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) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.HighCasedErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("ReservationRecommendationDetailsModel", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - 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 deleted file mode 100644 index 5f8707a5a5af..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_recommendations_operations.py +++ /dev/null @@ -1,188 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_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: 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), - } - - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReservationRecommendationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`reservation_recommendations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - 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 - includes '/subscriptions/{subscriptionId}/' for subscription scope, - '/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. 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 - allowed values ['VirtualMachines', 'SQLDatabases', 'PostgreSQL', 'ManagedDisk', 'MySQL', - 'RedHat', 'MariaDB', 'RedisCache', 'CosmosDB', 'SqlDataWarehouse', 'SUSELinux', 'AppService', - 'BlockBlob', 'AzureDataExplorer', 'VMwareCloudSimple'] and default value 'VirtualMachines'; and - properties/lookBackPeriod with allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and - 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{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 deleted file mode 100644 index ec4582467374..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservation_transactions_operations.py +++ /dev/null @@ -1,327 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_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: 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - } - - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - 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 -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), - "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), - } - - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReservationTransactionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`reservation_transactions` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - 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'. 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 ReservationTransaction or the result of - cls(response) - :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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/providers/Microsoft.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.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. 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'. 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 ModernReservationTransaction or the result of - cls(response) - :rtype: - ~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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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 deleted file mode 100644 index f4fb83276110..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_details_operations.py +++ /dev/null @@ -1,474 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_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: 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 - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - } - - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - 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 -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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 - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), - } - - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - resource_scope: str, - *, - 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 -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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), - } - - _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") - if end_date is not None: - _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if reservation_id is not None: - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReservationsDetailsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`reservations_details` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_reservation_order( - 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. 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'. 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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.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. Required. - :type reservation_order_id: str - :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'. 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_reservation_order_and_reservation.metadata = { - "url": "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationDetails" - } - - @distributed_trace - def list( - self, - resource_scope: str, - 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.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). Required. - :type resource_scope: str - :param start_date: Start date. Only applicable when querying with billing profile. Default - value is None. - :type start_date: str - :param end_date: End date. Only applicable when querying with billing profile. Default value is - None. - :type end_date: str - :param filter: Filter reservation details by date range. The properties/UsageDate for start - date and end date. The filter supports 'le' and 'ge'. Not applicable when querying with - billing profile. Default value is None. - :type filter: str - :param reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also provided. - Filter to a specific reservation. Default value is None. - :type reservation_id: str - :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. - 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=self.list.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{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 deleted file mode 100644 index d76164bcc81e..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_reservations_summaries_operations.py +++ /dev/null @@ -1,500 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_reservation_order_request( - 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: 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 - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - 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], - 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: 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 - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - resource_scope: str, - *, - 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 -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["grain"] = _SERIALIZER.query("grain", grain, "str") - if start_date is not None: - _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") - if end_date is not None: - _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if reservation_id is not None: - _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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReservationsSummariesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`reservations_summaries` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_reservation_order( - self, - reservation_order_id: str, - grain: Union[str, _models.Datagrain], - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - grain=grain, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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], - filter: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.ReservationSummary"]: - """Lists the reservations summaries for daily or monthly grain. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation. Required. - :type reservation_id: str - :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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - grain=grain, - filter=filter, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_by_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], - 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.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). Required. - :type resource_scope: str - :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. - :type start_date: str - :param end_date: End date. Only applicable when querying with billing profile. Default value is - None. - :type end_date: str - :param filter: Required only for daily grain. The properties/UsageDate for start date and end - date. The filter supports 'le' and 'ge'. Not applicable when querying with billing profile. - Default value is None. - :type filter: str - :param reservation_id: Reservation Id GUID. Only valid if reservationOrderId is also provided. - Filter to a specific reservation. Default value is None. - :type reservation_id: str - :param reservation_order_id: Reservation Order Id GUID. Required if reservationId is provided. - 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 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: 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, - 304: ResourceNotModifiedError, - } - 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, - grain=grain, - start_date=start_date, - end_date=end_date, - filter=filter, - reservation_id=reservation_id, - reservation_order_id=reservation_order_id, - api_version=api_version, - template_url=self.list.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{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 deleted file mode 100644 index cef15e36ba0c..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py +++ /dev/null @@ -1,151 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -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: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - 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), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class TagsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`tags` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, 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 - '/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 and - '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group - scope.. Required. - :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: TagsResult or None or the result of cls(response) - :rtype: ~azure.mgmt.consumption.models.TagsResult or None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: 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"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("TagsResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - 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 deleted file mode 100644 index 687fc9e04261..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_usage_details_operations.py +++ /dev/null @@ -1,244 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request( - scope: str, - *, - expand: Optional[str] = None, - filter: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = 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: 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), - } - - _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") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if skiptoken is not None: - _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if metric is not None: - _params["metric"] = _SERIALIZER.query("metric", metric, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class UsageDetailsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.consumption.ConsumptionManagementClient`'s - :attr:`usage_details` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, - scope: str, - expand: Optional[str] = None, - filter: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - metric: Optional[Union[str, _models.Metrictype]] = None, - **kwargs: Any - ) -> 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. - - :param scope: The scope associated with usage details operations. This includes - '/subscriptions/{subscriptionId}/' for subscription scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, - '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, - '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount - scope and '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management - Group scope. For subscription, billing account, department, enrollment account and management - group, you can also add billing period to the scope using - '/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}'. - Also, Modern Commerce Account scopes are - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount scope, - '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for billingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' - for invoiceSection scope, and - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. Required. - :type scope: str - :param 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 - details. Default value is None. - :type expand: str - :param filter: May be used to filter usageDetails by properties/resourceGroup, - properties/resourceName, properties/resourceId, properties/chargeType, - properties/reservationId, properties/publisherType or tags. The filter supports 'eq', 'lt', - 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is - a key value pair string where key and value is separated by a colon (:). PublisherType Filter - accepts two values azure and marketplace and it is currently supported for Web Direct Offer - Type. Default value is None. - :type filter: str - :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If - a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. Default - value is None. - :type skiptoken: str - :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. 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 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: 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, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_request( - scope=scope, - expand=expand, - filter=filter, - skiptoken=skiptoken, - top=top, - metric=metric, - 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) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - 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) # 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: 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]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{scope}/providers/Microsoft.Consumption/usageDetails"} diff --git a/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt b/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt index f802d9f73053..2e3da863badd 100644 --- a/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt +++ b/sdk/consumption/azure-mgmt-consumption/dev_requirements.txt @@ -1,3 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../resources/azure-mgmt-resource -../../identity/azure-identity \ No newline at end of file +../../identity/azure-identity +aiohttp \ No newline at end of file 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 index 3620ba064233..f54bd232555f 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostByManagementGroup.json +# x-ms-original-file: 2024-08-01/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 index 35594a0f8f15..f03b3bc3c90c 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostByManagementGroupFilterByDate.json +# x-ms-original-file: 2024-08-01/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 index 03f35dd50ae3..0248876a5a6d 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/AggregatedCostForBillingPeriodByManagementGroup.json +# x-ms-original-file: 2024-08-01/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 index cb29ed39ea58..1c581b7061d8 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BalancesByBillingAccount.json +# x-ms-original-file: 2024-08-01/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 index 149d33469f55..18af623e9d36 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BalancesByBillingAccountForBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 3d72c42e5a07..600c512cdb32 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/budget.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,7 +27,7 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.budgets.get( @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/Budget.json +# x-ms-original-file: 2024-08-01/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 index a07166094b71..d7fbafdd88c7 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/budgets_list.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,7 +27,7 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.budgets.list( @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/BudgetsList.json +# x-ms-original-file: 2024-08-01/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 index 2ce887e2d9f9..c86a3cb815b5 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesForBillingPeriodByDepartment.json +# x-ms-original-file: 2024-08-01/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 index c91466879da1..84adeef3c64e 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesForBillingPeriodByEnrollmentAccount.json +# x-ms-original-file: 2024-08-01/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 index c48bb008f4ac..778441fb62ae 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccount.json +# x-ms-original-file: 2024-08-01/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 index efd41b7b098a..ca674ee191c6 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByBillingProfileId.json +# x-ms-original-file: 2024-08-01/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 index 04b0cbddbc9f..73ccbd783900 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByCustomerId.json +# x-ms-original-file: 2024-08-01/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 index 7035f89b7016..47f1e461dcaa 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingAccountGroupByInvoiceSectionId.json +# x-ms-original-file: 2024-08-01/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 index 067b57bb7844..ab026677736b 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfile.json +# x-ms-original-file: 2024-08-01/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 index 1ae82b37718a..6967c31d5996 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfileGroupByInvoiceSectionId.json +# x-ms-original-file: 2024-08-01/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 index 613175dbc5a0..1327997db9a7 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernBillingProfileInvoiceSection.json +# x-ms-original-file: 2024-08-01/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 index 43c9070e4881..5ec04cc4bb34 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernCustomer.json +# x-ms-original-file: 2024-08-01/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 index 2a373da5182b..9c216ba8211c 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListByModernInvoiceSectionId.json +# x-ms-original-file: 2024-08-01/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 index 5f000f461b71..ceb036ee6e5a 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListForDepartmentFilterByStartEndDate.json +# x-ms-original-file: 2024-08-01/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 index 36be9fec7917..a74f8d0d2247 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ChargesListForEnrollmentAccountFilterByStartEndDate.json +# x-ms-original-file: 2024-08-01/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 index 979f6ed0c2b4..fb0be68de01d 100644 --- 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 @@ -1,12 +1,14 @@ +# pylint: disable=line-too-long,useless-suppression # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,7 +28,7 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.budgets.create_or_update( @@ -75,6 +77,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/CreateOrUpdateBudget.json +# x-ms-original-file: 2024-08-01/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 index e28aa54c136a..2b68b380a7cf 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/CreditSummaryByBillingProfile.json +# x-ms-original-file: 2024-08-01/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 index b8f8189f1e45..c827c5e26031 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/delete_budget.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,16 +27,15 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) - response = client.budgets.delete( + 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 +# x-ms-original-file: 2024-08-01/DeleteBudget.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/ea_price_sheet_for_billing_period.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/ea_price_sheet_for_billing_period.py new file mode 100644 index 000000000000..094b1597c460 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/ea_price_sheet_for_billing_period.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) Python 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 ea_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="SUBSCRIPTION_ID", + ) + + response = client.price_sheet.begin_download_by_billing_account_period( + billing_account_id="0000000", + billing_period_name="202305", + ).result() + print(response) + + +# x-ms-original-file: 2024-08-01/EAPriceSheetForBillingPeriod.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 index 654c39418ad4..dba866b3e9d3 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsGetByBillingAccount.json +# x-ms-original-file: 2024-08-01/EventsGetByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_contributor.py new file mode 100644 index 000000000000..3a989a5d3b94 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_contributor.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) Python 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_contributor.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: 2024-08-01/EventsGetByBillingAccount-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_primary.py new file mode 100644 index 000000000000..4326a9f3f37f --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_primary.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) Python 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_primary.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: 2024-08-01/EventsGetByBillingAccount-Primary.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 index 727edac86858..7e55c513090c 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsGetByBillingAccountWithFilters.json +# x-ms-original-file: 2024-08-01/EventsGetByBillingAccountWithFilters.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_contributor.py new file mode 100644 index 000000000000..2caf77d85767 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_contributor.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) Python 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_contributor.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: 2024-08-01/EventsGetByBillingAccountWithFilters-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_primary.py new file mode 100644 index 000000000000..49357acc5fa3 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/events_get_by_billing_account_with_filters_primary.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) Python 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_primary.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: 2024-08-01/EventsGetByBillingAccountWithFilters-Primary.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 index f84a0cec1ec3..00bc8b2f57c7 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -39,6 +40,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/EventsListByBillingProfile.json +# x-ms-original-file: 2024-08-01/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 index e63cf0b91405..9055a7698ebf 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingAccount.json +# x-ms-original-file: 2024-08-01/LotsListByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_contributor.py new file mode 100644 index 000000000000..325eb9a94f9c --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_contributor.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) Python 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_contributor.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: 2024-08-01/LotsListByBillingAccount-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_primary.py new file mode 100644 index 000000000000..f8bf40b03326 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_primary.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) Python 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_primary.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: 2024-08-01/LotsListByBillingAccount-Primary.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 index 76381e1425e0..c85b3717a7f3 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingAccountWithFilters.json +# x-ms-original-file: 2024-08-01/LotsListByBillingAccountWithFilters.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_contributor.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_contributor.py new file mode 100644 index 000000000000..4662776d07cb --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_contributor.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) Python 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_contributor.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: 2024-08-01/LotsListByBillingAccountWithFilters-Contributor.json +if __name__ == "__main__": + main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_primary.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_primary.py new file mode 100644 index 000000000000..fc2bca819e72 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/lots_list_by_billing_account_with_filters_primary.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) Python 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_primary.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: 2024-08-01/LotsListByBillingAccountWithFilters-Primary.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 index fe3344c1b346..cbad3b5f39b0 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByBillingProfile.json +# x-ms-original-file: 2024-08-01/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 index f5bb3322ebe5..8e6fa60a98a0 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByCustomer.json +# x-ms-original-file: 2024-08-01/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 index 74e95d98f92c..a601a9a634d3 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/LotsListByCustomerWithFilters.json +# x-ms-original-file: 2024-08-01/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 index 85fe45b1a08c..384fd7e9694f 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByBillingAccountList.json +# x-ms-original-file: 2024-08-01/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 index ff44044a915e..76e55e10cbd6 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByBillingAccountListForBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 022527d5f93e..93049c02dec0 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByDepartmentList.json +# x-ms-original-file: 2024-08-01/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 index 21aacd1cec54..29a00af9c5ec 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByDepartment_ListByBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 6ca5344dc699..8e2322596069 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByEnrollmentAccountList.json +# x-ms-original-file: 2024-08-01/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 index a8db1c7722ab..042e2efe09a1 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByEnrollmentAccounts_ListByBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 4ee9b750a604..e8c7382fd17e 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByManagementGroupList.json +# x-ms-original-file: 2024-08-01/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 index 1418bb34ebde..62284a923b8f 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesByManagementGroup_ListForBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 8db7d43c202b..49993db9453a 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/marketplaces_list.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,7 +27,7 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.marketplaces.list( @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesList.json +# x-ms-original-file: 2024-08-01/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 index cd0a50fb3de2..db30f039aa6d 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,7 +27,7 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.marketplaces.list( @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/MarketplacesListForBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 0aa0424ba67f..cb978d6bf272 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/operation_list.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -34,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/OperationList.json +# x-ms-original-file: 2024-08-01/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 index 50f503ce57fa..dd827c2225bf 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,13 +27,13 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.price_sheet.get() print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheet.json +# x-ms-original-file: 2024-08-01/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 index bb0b296619c5..b61d9892fcd2 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/price_sheet_expand.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,7 +27,7 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.price_sheet.get_by_billing_period( @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheetExpand.json +# x-ms-original-file: 2024-08-01/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 index f0fc2a5d6a78..5a869a121e74 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -26,7 +27,7 @@ def main(): client = ConsumptionManagementClient( credential=DefaultAzureCredential(), - subscription_id="00000000-0000-0000-0000-000000000000", + subscription_id="SUBSCRIPTION_ID", ) response = client.price_sheet.get_by_billing_period( @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/PriceSheetForBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 305bb208f4f7..ed69dacc0825 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_details.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetails.json +# x-ms-original-file: 2024-08-01/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 index ad1a1e3d3a2e..2de8a4107b68 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingAccountId.json +# x-ms-original-file: 2024-08-01/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 index 868b9badee5a..87f3a7638f03 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingProfileId.json +# x-ms-original-file: 2024-08-01/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 index 5e2576af19e9..c0c1fd974262 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsByBillingProfileIdReservationId.json +# x-ms-original-file: 2024-08-01/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 index 648185c1e6d3..36dfdf78cec7 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -38,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationDetailsWithReservationId.json +# x-ms-original-file: 2024-08-01/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 index b568ac4ebc9a..793d365752c9 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -30,7 +31,7 @@ def main(): ) response = client.reservation_recommendation_details.get( - resource_scope="providers/Microsoft.Billing/billingAccounts/000000", + resource_scope="providers/Microsoft.Billing/billingAccounts/00000000", scope="Shared", region="eastus", term="P1Y", @@ -40,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByBillingAccount.json +# x-ms-original-file: 2024-08-01/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 index baadc975b913..25c321d5602e 100644 --- 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 @@ -1,12 +1,14 @@ +# pylint: disable=line-too-long,useless-suppression # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -40,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByBillingProfile.json +# x-ms-original-file: 2024-08-01/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 index 24db1707a9eb..f115014c33b5 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -40,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsByResourceGroup.json +# x-ms-original-file: 2024-08-01/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 index 00fd41c3e879..b7bf0c2d1300 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -40,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationDetailsBySubscription.json +# x-ms-original-file: 2024-08-01/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 index b6e75bdc45ba..064172aad53f 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByBillingAccount.json +# x-ms-original-file: 2024-08-01/ReservationRecommendationsByBillingAccount.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account_filter_by_scope.py b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account_filter_by_scope.py new file mode 100644 index 000000000000..d8ae80501c0f --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_recommendations_by_billing_account_filter_by_scope.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) Python 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_filter_by_scope.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: 2024-08-01/ReservationRecommendationsByBillingAccountFilterByScope.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 index 34c18444bb67..49a766091d40 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByBillingProfile.json +# x-ms-original-file: 2024-08-01/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 index 38c93cb12b72..345e9c7ed2e0 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsByResourceGroup.json +# x-ms-original-file: 2024-08-01/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 index 6f3953bfafe0..8f9f59bfa55b 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsBySubscription.json +# x-ms-original-file: 2024-08-01/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 index b1eb8f1d440f..85aef9747e66 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationRecommendationsFilterBySubscriptionForScopeLookBackPeriod.json +# x-ms-original-file: 2024-08-01/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 index 483c4cc28fdc..7b39b3381c25 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_daily.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDaily.json +# x-ms-original-file: 2024-08-01/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 index c8cb54c7f501..024cba114756 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithBillingAccountId.json +# x-ms-original-file: 2024-08-01/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 index 026c74b73209..ad81fa638616 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithBillingProfileId.json +# x-ms-original-file: 2024-08-01/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 index fef5c801ffd3..7dab1d4d032a 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -38,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesDailyWithReservationId.json +# x-ms-original-file: 2024-08-01/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 index d422a0e92546..cfd1444d7d85 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/reservation_summaries_monthly.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthly.json +# x-ms-original-file: 2024-08-01/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 index 5364f59a6cdc..90559db003ac 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingAccountId.json +# x-ms-original-file: 2024-08-01/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 index 26e7ace88c0e..b9a994e9f819 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingProfileId.json +# x-ms-original-file: 2024-08-01/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 index ecce4ed58421..47dca093d2b1 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithBillingProfileIdReservationId.json +# x-ms-original-file: 2024-08-01/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 index 5d568bf216d2..f54063220218 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -38,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationSummariesMonthlyWithReservationId.json +# x-ms-original-file: 2024-08-01/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 index 47ad9d5fefe6..cba4943812d1 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationTransactionsListByBillingProfileId.json +# x-ms-original-file: 2024-08-01/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 index e981da502b4c..92ac66065c3c 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/ReservationTransactionsListByEnrollmentNumber.json +# x-ms-original-file: 2024-08-01/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 index d1687eeaea60..931a0832e9da 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/tags.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/Tags.json +# x-ms-original-file: 2024-08-01/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 index 1bd9e81a704a..543d0ef17610 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_expand.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsExpand.json +# x-ms-original-file: 2024-08-01/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 index 629b97dd45a8..c620f400af9d 100644 --- a/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py +++ b/sdk/consumption/azure-mgmt-consumption/generated_samples/usage_details_list.py @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsList.json +# x-ms-original-file: 2024-08-01/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 index b7670a59ed04..4370941ec461 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByBillingAccount.json +# x-ms-original-file: 2024-08-01/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 index 1ae750575929..0a87072de400 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByDepartment.json +# x-ms-original-file: 2024-08-01/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 index b30348d97760..a50251a4d91b 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByEnrollmentAccount.json +# x-ms-original-file: 2024-08-01/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 index bea5ad73b412..f0cf51b15a7b 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByManagementGroup.json +# x-ms-original-file: 2024-08-01/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 index fa5ce256e80a..37768e4eb784 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCABillingAccount.json +# x-ms-original-file: 2024-08-01/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 index 26898092a093..b0d04f21f24a 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCABillingProfile.json +# x-ms-original-file: 2024-08-01/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 index 9dc99a6b98a5..623344c1e859 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCACustomer.json +# x-ms-original-file: 2024-08-01/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 index 31956a23ef8d..4f4ae1aabdd4 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMCAInvoiceSection.json +# x-ms-original-file: 2024-08-01/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 index 74a175954cb5..d5fc410affcf 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricActualCost.json +# x-ms-original-file: 2024-08-01/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 index 8f8e9287f20e..e70a7b54b148 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricAmortizedCost.json +# x-ms-original-file: 2024-08-01/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 index 5fd433c0db0e..2ab08389063b 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListByMetricUsage.json +# x-ms-original-file: 2024-08-01/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 index 0f46035be369..4f2ee946ca23 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListFilterByTag.json +# x-ms-original-file: 2024-08-01/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 index 2bc29d159630..a6fd8c66385b 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriod.json +# x-ms-original-file: 2024-08-01/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 index 2f72f2a0cfb0..bca8fb922615 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByBillingAccount.json +# x-ms-original-file: 2024-08-01/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 index 462999a9dc8a..efdf91ad5869 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByDepartment.json +# x-ms-original-file: 2024-08-01/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 index ffec807c47c5..d3ec370fae32 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByEnrollmentAccount.json +# x-ms-original-file: 2024-08-01/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 index dce956c8dbd4..193ce797fc52 100644 --- 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 @@ -2,11 +2,12 @@ # -------------------------------------------------------------------------- # 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. +# Code generated by Microsoft (R) Python 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 """ @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/consumption/resource-manager/Microsoft.Consumption/stable/2021-10-01/examples/UsageDetailsListForBillingPeriodByManagementGroup.json +# x-ms-original-file: 2024-08-01/UsageDetailsListForBillingPeriodByManagementGroup.json if __name__ == "__main__": main() diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/conftest.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/conftest.py new file mode 100644 index 000000000000..838ec13d349e --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/conftest.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + consumptionmanagement_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + consumptionmanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + consumptionmanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + consumptionmanagement_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer( + regex=consumptionmanagement_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=consumptionmanagement_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=consumptionmanagement_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=consumptionmanagement_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations.py new file mode 100644 index 000000000000..9fe98444adcf --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementAggregatedCostOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_aggregated_cost_get_by_management_group(self, resource_group): + response = self.client.aggregated_cost.get_by_management_group( + management_group_id="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_aggregated_cost_get_for_billing_period_by_management_group(self, resource_group): + response = self.client.aggregated_cost.get_for_billing_period_by_management_group( + management_group_id="str", + billing_period_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations_async.py new file mode 100644 index 000000000000..6b4872fb5539 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_aggregated_cost_operations_async.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementAggregatedCostOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_aggregated_cost_get_by_management_group(self, resource_group): + response = await self.client.aggregated_cost.get_by_management_group( + management_group_id="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_aggregated_cost_get_for_billing_period_by_management_group(self, resource_group): + response = await self.client.aggregated_cost.get_for_billing_period_by_management_group( + management_group_id="str", + billing_period_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations.py new file mode 100644 index 000000000000..22dda7645781 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementBalancesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_balances_get_by_billing_account(self, resource_group): + response = self.client.balances.get_by_billing_account( + billing_account_id="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_balances_get_for_billing_period_by_billing_account(self, resource_group): + response = self.client.balances.get_for_billing_period_by_billing_account( + billing_account_id="str", + billing_period_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations_async.py new file mode 100644 index 000000000000..edff55b87dd2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_balances_operations_async.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementBalancesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_balances_get_by_billing_account(self, resource_group): + response = await self.client.balances.get_by_billing_account( + billing_account_id="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_balances_get_for_billing_period_by_billing_account(self, resource_group): + response = await self.client.balances.get_for_billing_period_by_billing_account( + billing_account_id="str", + billing_period_name="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations.py new file mode 100644 index 000000000000..a7c720a1431b --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations.py @@ -0,0 +1,106 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementBudgetsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_get(self, resource_group): + response = self.client.budgets.get( + scope="str", + budget_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_create_or_update(self, resource_group): + response = self.client.budgets.create_or_update( + scope="str", + budget_name="str", + parameters={ + "eTag": "str", + "id": "str", + "name": "str", + "properties": { + "amount": 0.0, + "category": "str", + "timeGrain": "str", + "timePeriod": {"startDate": "2020-02-20 00:00:00", "endDate": "2020-02-20 00:00:00"}, + "currentSpend": {"amount": 0.0, "unit": "str"}, + "filter": { + "and": [ + { + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + } + ], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "forecastSpend": {"amount": 0.0, "unit": "str"}, + "notifications": { + "str": { + "contactEmails": ["str"], + "enabled": bool, + "operator": "str", + "threshold": 0.0, + "contactGroups": ["str"], + "contactRoles": ["str"], + "locale": "str", + "thresholdType": "str", + } + }, + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_delete(self, resource_group): + response = self.client.budgets.delete( + scope="str", + budget_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_budgets_list(self, resource_group): + response = self.client.budgets.list( + scope="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations_async.py new file mode 100644 index 000000000000..3c09c65f4186 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_budgets_operations_async.py @@ -0,0 +1,107 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementBudgetsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_get(self, resource_group): + response = await self.client.budgets.get( + scope="str", + budget_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_create_or_update(self, resource_group): + response = await self.client.budgets.create_or_update( + scope="str", + budget_name="str", + parameters={ + "eTag": "str", + "id": "str", + "name": "str", + "properties": { + "amount": 0.0, + "category": "str", + "timeGrain": "str", + "timePeriod": {"startDate": "2020-02-20 00:00:00", "endDate": "2020-02-20 00:00:00"}, + "currentSpend": {"amount": 0.0, "unit": "str"}, + "filter": { + "and": [ + { + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + } + ], + "dimensions": {"name": "str", "operator": "str", "values": ["str"]}, + "tags": {"name": "str", "operator": "str", "values": ["str"]}, + }, + "forecastSpend": {"amount": 0.0, "unit": "str"}, + "notifications": { + "str": { + "contactEmails": ["str"], + "enabled": bool, + "operator": "str", + "threshold": 0.0, + "contactGroups": ["str"], + "contactRoles": ["str"], + "locale": "str", + "thresholdType": "str", + } + }, + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_delete(self, resource_group): + response = await self.client.budgets.delete( + scope="str", + budget_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_budgets_list(self, resource_group): + response = self.client.budgets.list( + scope="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations.py new file mode 100644 index 000000000000..e8f3db5eb2e9 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations.py @@ -0,0 +1,29 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementChargesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_charges_list(self, resource_group): + response = self.client.charges.list( + scope="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations_async.py new file mode 100644 index 000000000000..5d98dd1def25 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_charges_operations_async.py @@ -0,0 +1,30 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementChargesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_charges_list(self, resource_group): + response = await self.client.charges.list( + scope="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations.py new file mode 100644 index 000000000000..194cd2e88d84 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations.py @@ -0,0 +1,30 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementCreditsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_credits_get(self, resource_group): + response = self.client.credits.get( + billing_account_id="str", + billing_profile_id="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations_async.py new file mode 100644 index 000000000000..85419b34dfdb --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_credits_operations_async.py @@ -0,0 +1,31 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementCreditsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_credits_get(self, resource_group): + response = await self.client.credits.get( + billing_account_id="str", + billing_profile_id="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations.py new file mode 100644 index 000000000000..6398286fb1b2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementEventsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_events_list_by_billing_profile(self, resource_group): + response = self.client.events.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + start_date="str", + end_date="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_events_list_by_billing_account(self, resource_group): + response = self.client.events.list_by_billing_account( + billing_account_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations_async.py new file mode 100644 index 000000000000..b7bc7f238f09 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_events_operations_async.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementEventsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_events_list_by_billing_profile(self, resource_group): + response = self.client.events.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + start_date="str", + end_date="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_events_list_by_billing_account(self, resource_group): + response = self.client.events.list_by_billing_account( + billing_account_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations.py new file mode 100644 index 000000000000..03ca011b307d --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementLotsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_lots_list_by_billing_profile(self, resource_group): + response = self.client.lots.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_lots_list_by_billing_account(self, resource_group): + response = self.client.lots.list_by_billing_account( + billing_account_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_lots_list_by_customer(self, resource_group): + response = self.client.lots.list_by_customer( + billing_account_id="str", + customer_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations_async.py new file mode 100644 index 000000000000..a8063612745e --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_lots_operations_async.py @@ -0,0 +1,52 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementLotsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_lots_list_by_billing_profile(self, resource_group): + response = self.client.lots.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_lots_list_by_billing_account(self, resource_group): + response = self.client.lots.list_by_billing_account( + billing_account_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_lots_list_by_customer(self, resource_group): + response = self.client.lots.list_by_customer( + billing_account_id="str", + customer_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations.py new file mode 100644 index 000000000000..a5b01167b869 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations.py @@ -0,0 +1,29 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementMarketplacesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_marketplaces_list(self, resource_group): + response = self.client.marketplaces.list( + scope="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations_async.py new file mode 100644 index 000000000000..6ce71ff0e3e8 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_marketplaces_operations_async.py @@ -0,0 +1,30 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementMarketplacesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_marketplaces_list(self, resource_group): + response = self.client.marketplaces.list( + scope="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations.py new file mode 100644 index 000000000000..5a6bc207dd23 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations.py @@ -0,0 +1,27 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations_async.py new file mode 100644 index 000000000000..20b0f69b2845 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_operations_async.py @@ -0,0 +1,28 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations.py new file mode 100644 index 000000000000..53a5e64ceef2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementPriceSheetOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_get_by_billing_period(self, resource_group): + response = self.client.price_sheet.get_by_billing_period( + billing_period_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_get(self, resource_group): + response = self.client.price_sheet.get() + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_begin_download_by_billing_account_period(self, resource_group): + response = self.client.price_sheet.begin_download_by_billing_account_period( + billing_account_id="str", + billing_period_name="str", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations_async.py new file mode 100644 index 000000000000..f5e66c1fadb3 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_price_sheet_operations_async.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementPriceSheetOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_get_by_billing_period(self, resource_group): + response = await self.client.price_sheet.get_by_billing_period( + billing_period_name="str", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_get(self, resource_group): + response = await self.client.price_sheet.get() + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_begin_download_by_billing_account_period(self, resource_group): + response = await ( + await self.client.price_sheet.begin_download_by_billing_account_period( + billing_account_id="str", + billing_period_name="str", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations.py new file mode 100644 index 000000000000..1a49ecb84eda --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations.py @@ -0,0 +1,34 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationRecommendationDetailsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_recommendation_details_get(self, resource_group): + response = self.client.reservation_recommendation_details.get( + resource_scope="str", + scope="str", + region="str", + term="str", + look_back_period="str", + product="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations_async.py new file mode 100644 index 000000000000..facdd1c31655 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendation_details_operations_async.py @@ -0,0 +1,35 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationRecommendationDetailsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_recommendation_details_get(self, resource_group): + response = await self.client.reservation_recommendation_details.get( + resource_scope="str", + scope="str", + region="str", + term="str", + look_back_period="str", + product="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations.py new file mode 100644 index 000000000000..0365ee3c6746 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations.py @@ -0,0 +1,29 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationRecommendationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_recommendations_list(self, resource_group): + response = self.client.reservation_recommendations.list( + resource_scope="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations_async.py new file mode 100644 index 000000000000..64529a5e1827 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_recommendations_operations_async.py @@ -0,0 +1,30 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationRecommendationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_recommendations_list(self, resource_group): + response = self.client.reservation_recommendations.list( + resource_scope="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations.py new file mode 100644 index 000000000000..7beee6df7be6 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationTransactionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_transactions_list(self, resource_group): + response = self.client.reservation_transactions.list( + billing_account_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_transactions_list_by_billing_profile(self, resource_group): + response = self.client.reservation_transactions.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations_async.py new file mode 100644 index 000000000000..ea2e4eb868b3 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservation_transactions_operations_async.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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationTransactionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_transactions_list(self, resource_group): + response = self.client.reservation_transactions.list( + billing_account_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_transactions_list_by_billing_profile(self, resource_group): + response = self.client.reservation_transactions.list_by_billing_profile( + billing_account_id="str", + billing_profile_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations.py new file mode 100644 index 000000000000..419edc4a49f9 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations.py @@ -0,0 +1,52 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationsDetailsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_details_list_by_reservation_order(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order( + reservation_order_id="str", + filter="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_details_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + filter="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_details_list(self, resource_group): + response = self.client.reservations_details.list( + resource_scope="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations_async.py new file mode 100644 index 000000000000..93e8d3ec5221 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_details_operations_async.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationsDetailsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_details_list_by_reservation_order(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order( + reservation_order_id="str", + filter="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_details_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_details.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + filter="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_details_list(self, resource_group): + response = self.client.reservations_details.list( + resource_scope="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations.py new file mode 100644 index 000000000000..632ca42a850f --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationsSummariesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_summaries_list_by_reservation_order(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order( + reservation_order_id="str", + grain="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_summaries_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + grain="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservations_summaries_list(self, resource_group): + response = self.client.reservations_summaries.list( + resource_scope="str", + grain="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations_async.py new file mode 100644 index 000000000000..c20b4072c2a9 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_reservations_summaries_operations_async.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementReservationsSummariesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_summaries_list_by_reservation_order(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order( + reservation_order_id="str", + grain="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_summaries_list_by_reservation_order_and_reservation(self, resource_group): + response = self.client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id="str", + reservation_id="str", + grain="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservations_summaries_list(self, resource_group): + response = self.client.reservations_summaries.list( + resource_scope="str", + grain="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations.py new file mode 100644 index 000000000000..28524b477218 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations.py @@ -0,0 +1,29 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementTagsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_tags_get(self, resource_group): + response = self.client.tags.get( + scope="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations_async.py new file mode 100644 index 000000000000..0e342f421cf7 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_tags_operations_async.py @@ -0,0 +1,30 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementTagsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_tags_get(self, resource_group): + response = await self.client.tags.get( + scope="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations.py new file mode 100644 index 000000000000..ab87730b1a17 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations.py @@ -0,0 +1,29 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementUsageDetailsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_usage_details_list(self, resource_group): + response = self.client.usage_details.list( + scope="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations_async.py b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations_async.py new file mode 100644 index 000000000000..a4ef0f631133 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/generated_tests/test_consumption_management_usage_details_operations_async.py @@ -0,0 +1,30 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestConsumptionManagementUsageDetailsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_usage_details_list(self, resource_group): + response = self.client.usage_details.list( + scope="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/consumption/azure-mgmt-consumption/pyproject.toml b/sdk/consumption/azure-mgmt-consumption/pyproject.toml index 540da07d41af..232c40e6a2dc 100644 --- a/sdk/consumption/azure-mgmt-consumption/pyproject.toml +++ b/sdk/consumption/azure-mgmt-consumption/pyproject.toml @@ -1,6 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-consumption" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Consumption Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.10" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.consumption._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + [tool.azure-sdk-build] breaking = false mypy = false pyright = false type_check_samples = false verifytypes = false + +[packaging] +package_name = "azure-mgmt-consumption" +package_nspkg = "azure-mgmt-nspkg" +package_pprint_name = "Consumption" +package_doc_id = "consumption" +is_stable = false +is_arm = true +sample_link = "" +title = "ConsumptionManagementClient" +need_msrestazure = false +need_azuremgmtcore = true +exclude_folders = "" diff --git a/sdk/consumption/azure-mgmt-consumption/sdk_packaging.toml b/sdk/consumption/azure-mgmt-consumption/sdk_packaging.toml deleted file mode 100644 index 17190cce32d8..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/sdk_packaging.toml +++ /dev/null @@ -1,9 +0,0 @@ -[packaging] -package_name = "azure-mgmt-consumption" -package_nspkg = "azure-mgmt-nspkg" -package_pprint_name = "Consumption" -package_doc_id = "consumption" -is_stable = false -is_arm = true -sample_link = "" -title = "ConsumptionManagementClient" diff --git a/sdk/consumption/azure-mgmt-consumption/setup.py b/sdk/consumption/azure-mgmt-consumption/setup.py deleted file mode 100644 index 58c2d0310b71..000000000000 --- a/sdk/consumption/azure-mgmt-consumption/setup.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python - -#------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -#-------------------------------------------------------------------------- - -import re -import os.path -from io import open -from setuptools import find_packages, setup - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-mgmt-consumption" -PACKAGE_PPRINT_NAME = "Consumption" - -# a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') -# a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') - -# Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, 'version.py') - if os.path.exists(os.path.join(package_folder_path, 'version.py')) - else os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) - -if not version: - raise RuntimeError('Cannot find version information') - -with open('README.md', encoding='utf-8') as f: - readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: - changelog = f.read() - -setup( - name=PACKAGE_NAME, - version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', - keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product - classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'License :: OSI Approved :: MIT License', - ], - zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.mgmt', - ]), - include_package_data=True, - package_data={ - 'pytyped': ['py.typed'], - }, - install_requires=[ - "msrest>=0.7.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", - ], - python_requires=">=3.7" -) diff --git a/sdk/consumption/azure-mgmt-consumption/tests/conftest.py b/sdk/consumption/azure-mgmt-consumption/tests/conftest.py index e7981d635f56..838ec13d349e 100644 --- a/sdk/consumption/azure-mgmt-consumption/tests/conftest.py +++ b/sdk/consumption/azure-mgmt-consumption/tests/conftest.py @@ -1,55 +1,39 @@ +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import os -import platform import pytest -import sys - from dotenv import load_dotenv - -from devtools_testutils import test_proxy, add_general_regex_sanitizer -from devtools_testutils import add_header_regex_sanitizer, add_body_key_sanitizer - -# Ignore async tests for Python < 3.5 -collect_ignore_glob = [] -if sys.version_info < (3, 5) or platform.python_implementation() == "PyPy": - collect_ignore_glob.append("*_async.py") +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) load_dotenv() + +# For security, please avoid record sensitive identity information in recordings @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): - subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") - client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=client_secret, value="00000000-0000-0000-0000-000000000000") + consumptionmanagement_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + consumptionmanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + consumptionmanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + consumptionmanagement_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer( + regex=consumptionmanagement_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=consumptionmanagement_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=consumptionmanagement_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=consumptionmanagement_client_secret, value="00000000-0000-0000-0000-000000000000") + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") add_header_regex_sanitizer(key="Cookie", value="cookie;") - add_body_key_sanitizer(json_path="$..access_token", value="access_token") \ No newline at end of file + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/consumption/azure-mgmt-consumption/tests/test_budgets.py b/sdk/consumption/azure-mgmt-consumption/tests/test_budgets.py index c9eb5e1ca150..7d2ba286eccb 100644 --- a/sdk/consumption/azure-mgmt-consumption/tests/test_budgets.py +++ b/sdk/consumption/azure-mgmt-consumption/tests/test_budgets.py @@ -16,27 +16,22 @@ class TestMgmtConsumption(AzureMgmtRecordedTestCase): def setup_method(self, method): - self.consumption_client = self.create_mgmt_client( - azure.mgmt.consumption.ConsumptionManagementClient - ) + self.consumption_client = self.create_mgmt_client(azure.mgmt.consumption.ConsumptionManagementClient) @ResourceGroupPreparer() @recorded_by_proxy def test_budgets(self, resource_group): - SUBSCRIPTION_ID = self.get_settings_value('SUBSCRIPTION_ID') - SCOPE = '/subscriptions/{}/resourceGroups/{}'.format(SUBSCRIPTION_ID, resource_group.name) - BUDGET_NAME = self.get_resource_name('budget') + SUBSCRIPTION_ID = self.get_settings_value("SUBSCRIPTION_ID") + SCOPE = "/subscriptions/{}/resourceGroups/{}".format(SUBSCRIPTION_ID, resource_group.name) + BUDGET_NAME = self.get_resource_name("budget") start_date = "2022-12-01T00:00:00.000Z" - end_date = "2023-06-01T00:00:00.000Z" + end_date = "2023-06-01T00:00:00.000Z" # create BODY = { "category": "Cost", - "amount": '100', + "amount": "100", "timeGrain": "Monthly", - "timePeriod": { - "startDate": start_date, - "endDate": end_date - } + "timePeriod": {"startDate": start_date, "endDate": end_date}, } self.consumption_client.budgets.create_or_update(SCOPE, BUDGET_NAME, BODY) @@ -48,5 +43,5 @@ def test_budgets(self, resource_group): # ------------------------------------------------------------------------------ -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_operations_async_test.py b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_operations_async_test.py new file mode 100644 index 000000000000..59eedc7bf531 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_operations_async_test.py @@ -0,0 +1,27 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestConsumptionManagementOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r async for r in response] + assert len(result) >= 0 diff --git a/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_operations_test.py b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_operations_test.py new file mode 100644 index 000000000000..75de2e1ca6f8 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_operations_test.py @@ -0,0 +1,26 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestConsumptionManagementOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list() + result = [r for r in response] + assert len(result) >= 0 diff --git a/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_price_sheet_operations_async_test.py b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_price_sheet_operations_async_test.py new file mode 100644 index 000000000000..f340225428d2 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_price_sheet_operations_async_test.py @@ -0,0 +1,27 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption.aio import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestConsumptionManagementPriceSheetOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_price_sheet_get(self, resource_group): + response = await self.client.price_sheet.get() + + assert response is not None diff --git a/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_price_sheet_operations_test.py b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_price_sheet_operations_test.py new file mode 100644 index 000000000000..016de0c8acc9 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/tests/test_consumption_management_price_sheet_operations_test.py @@ -0,0 +1,26 @@ +# 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) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.consumption import ConsumptionManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestConsumptionManagementPriceSheetOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ConsumptionManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_price_sheet_get(self, resource_group): + response = self.client.price_sheet.get() + + assert response is not None diff --git a/sdk/consumption/azure-mgmt-consumption/tests/test_mgmt_consumption.py b/sdk/consumption/azure-mgmt-consumption/tests/test_mgmt_consumption.py index 2cf2bee69f99..99a375ca295f 100644 --- a/sdk/consumption/azure-mgmt-consumption/tests/test_mgmt_consumption.py +++ b/sdk/consumption/azure-mgmt-consumption/tests/test_mgmt_consumption.py @@ -1,10 +1,10 @@ # 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. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import datetime import unittest @@ -12,21 +12,22 @@ import azure.mgmt.consumption.models from devtools_testutils import AzureMgmtRecordedTestCase, ResourceGroupPreparer, recorded_by_proxy -raise unittest.SkipTest("These were written by Consumption service team for 2.0.0 and would need adaption, and are disabled for now.") +raise unittest.SkipTest( + "These were written by Consumption service team for 2.0.0 and would need adaption, and are disabled for now." +) + class TestMgmtConsumption(AzureMgmtRecordedTestCase): - reservationOrderId = 'ca69259e-bd4f-45c3-bf28-3f353f9cce9b' - reservationId = 'f37f4b70-52ba-4344-a8bd-28abfd21d640' - billingPeriodName = '201710' - startDate = '2018-02-01T00:00:00Z' - endDate = '2018-02-28T00:00:00Z' + reservationOrderId = "ca69259e-bd4f-45c3-bf28-3f353f9cce9b" + reservationId = "f37f4b70-52ba-4344-a8bd-28abfd21d640" + billingPeriodName = "201710" + startDate = "2018-02-01T00:00:00Z" + endDate = "2018-02-28T00:00:00Z" models = azure.mgmt.consumption.models def setup_method(self, method): - self.consumption_client = self.create_mgmt_client( - azure.mgmt.consumption.ConsumptionManagementClient - ) + self.consumption_client = self.create_mgmt_client(azure.mgmt.consumption.ConsumptionManagementClient) def _validate_usage(self, usage, include_meter_details=False, include_additional_properties=False): assert usage is not None @@ -126,8 +127,8 @@ def test_consumption_subscription_usage(self): @recorded_by_proxy def test_consumption_subscription_usage_filter(self): - date_filter ='usageEnd le '+ str(MgmtConsumptionTest.endDate) - pages = self.consumption_client.usage_details.list(expand='meterDetails', filter=date_filter, top=10) + date_filter = "usageEnd le " + str(MgmtConsumptionTest.endDate) + pages = self.consumption_client.usage_details.list(expand="meterDetails", filter=date_filter, top=10) first_page = pages.advance_page() output = list(first_page) assert 10 == len(output) @@ -135,95 +136,167 @@ def test_consumption_subscription_usage_filter(self): @recorded_by_proxy def test_consumption_billing_period_usage(self): - output = list(self.consumption_client.usage_details.list(expand='properties/additionalProperties')) + output = list(self.consumption_client.usage_details.list(expand="properties/additionalProperties")) self._validate_usage(output[0], include_additional_properties=True) @recorded_by_proxy def test_consumption_billing_period_usage_filter(self): - output = list(self.consumption_client.usage_details.list_by_billing_period(billing_period_name=MgmtConsumptionTest.billingPeriodName, expand='properties/meterDetails,properties/additionalProperties', filter='usageEnd eq 2017-10-26T23:59:59Z')) + output = list( + self.consumption_client.usage_details.list_by_billing_period( + billing_period_name=MgmtConsumptionTest.billingPeriodName, + expand="properties/meterDetails,properties/additionalProperties", + filter="usageEnd eq 2017-10-26T23:59:59Z", + ) + ) self._validate_usage(output[0], include_meter_details=True, include_additional_properties=True) @recorded_by_proxy def test_consumption_reservations_summaries_monthly(self): - output = list(self.consumption_client.reservations_summaries.list_by_reservation_order(reservation_order_id=MgmtConsumptionTest.reservationOrderId, grain="monthly")) + output = list( + self.consumption_client.reservations_summaries.list_by_reservation_order( + reservation_order_id=MgmtConsumptionTest.reservationOrderId, grain="monthly" + ) + ) self._validate_reservations_summaries(output[0]) @recorded_by_proxy def test_consumption_reservations_summaries_monthly_withreservationid(self): - output = list(self.consumption_client.reservations_summaries.list_by_reservation_order_and_reservation(reservation_order_id=MgmtConsumptionTest.reservationOrderId, reservation_id=MgmtConsumptionTest.reservationId, grain="monthly")) + output = list( + self.consumption_client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id=MgmtConsumptionTest.reservationOrderId, + reservation_id=MgmtConsumptionTest.reservationId, + grain="monthly", + ) + ) self._validate_reservations_summaries(output[0]) @recorded_by_proxy def test_consumption_reservations_summaries_daily(self): - output = list(self.consumption_client.reservations_summaries.list_by_reservation_order(reservation_order_id=MgmtConsumptionTest.reservationOrderId, grain="daily", filter='properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-07')) + output = list( + self.consumption_client.reservations_summaries.list_by_reservation_order( + reservation_order_id=MgmtConsumptionTest.reservationOrderId, + grain="daily", + filter="properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-07", + ) + ) self._validate_reservations_summaries(output[0]) @recorded_by_proxy def test_consumption_reservation_summaries_daily_withreservationid(self): - output = list(self.consumption_client.reservations_summaries.list_by_reservation_order_and_reservation(reservation_order_id=MgmtConsumptionTest.reservationOrderId, reservation_id=MgmtConsumptionTest.reservationId, grain="daily", filter='properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-07')) + output = list( + self.consumption_client.reservations_summaries.list_by_reservation_order_and_reservation( + reservation_order_id=MgmtConsumptionTest.reservationOrderId, + reservation_id=MgmtConsumptionTest.reservationId, + grain="daily", + filter="properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-07", + ) + ) self._validate_reservations_summaries(output[0]) @recorded_by_proxy def test_consumption_reservations_details(self): - output = list(self.consumption_client.reservations_details.list_by_reservation_order(reservation_order_id=MgmtConsumptionTest.reservationOrderId, filter='properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-08')) + output = list( + self.consumption_client.reservations_details.list_by_reservation_order( + reservation_order_id=MgmtConsumptionTest.reservationOrderId, + filter="properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-08", + ) + ) self._validate_reservations_details(output[0]) @recorded_by_proxy def test_consumption_reservations_details_withreservationid(self): - output = list(self.consumption_client.reservations_details.list_by_reservation_order_and_reservation(reservation_order_id=MgmtConsumptionTest.reservationOrderId, reservation_id=MgmtConsumptionTest.reservationId, filter='properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-08')) + output = list( + self.consumption_client.reservations_details.list_by_reservation_order_and_reservation( + reservation_order_id=MgmtConsumptionTest.reservationOrderId, + reservation_id=MgmtConsumptionTest.reservationId, + filter="properties/UsageDate ge 2017-10-01 AND properties/UsageDate le 2017-12-08", + ) + ) self._validate_reservations_details(output[0]) @recorded_by_proxy def test_consumption_budget_get_by_resource_group(self): - budget = self.consumption_client.budgets.get(resource_groups='testscaleset', budget_name='PythonSDKTestBudgetCost8') + budget = self.consumption_client.budgets.get( + resource_groups="testscaleset", budget_name="PythonSDKTestBudgetCost8" + ) self._validate_budget(budget) @recorded_by_proxy def test_consumption_budget_update_By_resourceGroup(self): - budget = self.consumption_client.budgets.get(resource_groups='testscaleset', budget_name='PythonSDKTestBudgetCost8') + budget = self.consumption_client.budgets.get( + resource_groups="testscaleset", budget_name="PythonSDKTestBudgetCost8" + ) budget.amount = 90.0 - budget.time_period = self.models.BudgetTimePeriod(start_date=budget.time_period.start_date, end_date=MgmtConsumptionTest.endDate) - output = self.consumption_client.budgets.create_or_update_by_resource_group_name(resource_group_name='testscaleset', budget_name='PythonSDKTestBudgetCost8', parameters=budget) - assert 'PythonSDKTestBudgetCost8' == output.name + budget.time_period = self.models.BudgetTimePeriod( + start_date=budget.time_period.start_date, end_date=MgmtConsumptionTest.endDate + ) + output = self.consumption_client.budgets.create_or_update_by_resource_group_name( + resource_group_name="testscaleset", budget_name="PythonSDKTestBudgetCost8", parameters=budget + ) + assert "PythonSDKTestBudgetCost8" == output.name assert 90.0 == output.amount @recorded_by_proxy def test_consumption_budget_delete_by_budget_resource_group_name(self): - budget = self.consumption_client.budgets.get(resource_groups='testscaleset', budget_name='PythonSDKTestBudgetCost8') + budget = self.consumption_client.budgets.get( + resource_groups="testscaleset", budget_name="PythonSDKTestBudgetCost8" + ) self._validate_budget(budget) - self.consumption_client.budgets.delete_by_resource_group_name(resource_group_name='testscaleset', budget_name=budget.name) + self.consumption_client.budgets.delete_by_resource_group_name( + resource_group_name="testscaleset", budget_name=budget.name + ) @recorded_by_proxy def test_consumption_budget_delete_by_budgetname(self): - budget = self.consumption_client.budgets.get(budget_name='PythonSDKTestBudgetCost') + budget = self.consumption_client.budgets.get(budget_name="PythonSDKTestBudgetCost") self._validate_budget(budget) self.consumption_client.budgets.delete(budget_name=budget.name) @recorded_by_proxy def test_consumption_budget_create(self): - budget = self.models.Budget(category=self.models.CategoryType.cost, amount=60.0, time_grain=self.models.TimeGrainType.monthly, time_period=self.models.BudgetTimePeriod(start_date=MgmtConsumptionTest.startDate, end_date=MgmtConsumptionTest.endDate)) - output = self.consumption_client.budgets.create_or_update(resource_group_name='testResource1', budget_name='PythonSDKTestBudgetCost', parameters=budget) - assert 'PythonSDKTestBudgetCost' == output.name + budget = self.models.Budget( + category=self.models.CategoryType.cost, + amount=60.0, + time_grain=self.models.TimeGrainType.monthly, + time_period=self.models.BudgetTimePeriod( + start_date=MgmtConsumptionTest.startDate, end_date=MgmtConsumptionTest.endDate + ), + ) + output = self.consumption_client.budgets.create_or_update( + resource_group_name="testResource1", budget_name="PythonSDKTestBudgetCost", parameters=budget + ) + assert "PythonSDKTestBudgetCost" == output.name @recorded_by_proxy def test_consumption_budget_get_by_budget_name(self): - budget = self.consumption_client.budgets.get(budget_name='PythonSDKTestBudgetCost8') + budget = self.consumption_client.budgets.get(budget_name="PythonSDKTestBudgetCost8") self._validate_budget(budget) @recorded_by_proxy def test_consumption_budget_update_and_get(self): - budget = self.consumption_client.budgets.get(budget_name='PythonSDKTestBudgetCost1') + budget = self.consumption_client.budgets.get(budget_name="PythonSDKTestBudgetCost1") budget.amount = 80.0 - budget.time_period = self.models.BudgetTimePeriod(start_date=budget.time_period.start_date, end_date=MgmtConsumptionTest.endDate) - self.consumption_client.budgets.create_or_update(budget_name='PythonSDKTestBudgetCost1', parameters=budget) - budget = self.consumption_client.budgets.get(budget_name='PythonSDKTestBudgetCost1') + budget.time_period = self.models.BudgetTimePeriod( + start_date=budget.time_period.start_date, end_date=MgmtConsumptionTest.endDate + ) + self.consumption_client.budgets.create_or_update(budget_name="PythonSDKTestBudgetCost1", parameters=budget) + budget = self.consumption_client.budgets.get(budget_name="PythonSDKTestBudgetCost1") self._validate_budget(budget) @recorded_by_proxy def test_consumption_budget_list(self): - budget = self.models.Budget(category=self.models.CategoryType.cost, amount=60.0, time_grain=self.models.TimeGrainType.monthly, time_period=self.models.BudgetTimePeriod(start_date=MgmtConsumptionTest.startDate, end_date=MgmtConsumptionTest.endDate)) - output = self.consumption_client.budgets.create_or_update(budget_name='PythonSDKTestBudgetCostCreateAndDelete', parameters=budget) - assert 'PythonSDKTestBudgetCostCreateAndDelete' == output.name + budget = self.models.Budget( + category=self.models.CategoryType.cost, + amount=60.0, + time_grain=self.models.TimeGrainType.monthly, + time_period=self.models.BudgetTimePeriod( + start_date=MgmtConsumptionTest.startDate, end_date=MgmtConsumptionTest.endDate + ), + ) + output = self.consumption_client.budgets.create_or_update( + budget_name="PythonSDKTestBudgetCostCreateAndDelete", parameters=budget + ) + assert "PythonSDKTestBudgetCostCreateAndDelete" == output.name self.consumption_client.budgets.delete(budget_name=output.name) @recorded_by_proxy @@ -236,7 +309,7 @@ def test_consumption_subscription_marketplace(self): @recorded_by_proxy def test_consumption_subscription_marketplace_filter(self): - pages = self.consumption_client.marketplaces.list(filter='usageEnd le 2018-02-02', top=1) + pages = self.consumption_client.marketplaces.list(filter="usageEnd le 2018-02-02", top=1) first_page = pages.advance_page() output = list(first_page) assert 1 == len(output) @@ -244,26 +317,30 @@ def test_consumption_subscription_marketplace_filter(self): @recorded_by_proxy def test_consumption_billing_period_marketplace(self): - pages = self.consumption_client.marketplaces.list_by_billing_period(billing_period_name='201804-1') + pages = self.consumption_client.marketplaces.list_by_billing_period(billing_period_name="201804-1") first_page = pages.advance_page() output = list(first_page) self._validate_marketplace(output[0]) @recorded_by_proxy def test_consumption_billing_period_marketplace_filter(self): - pages = self.consumption_client.marketplaces.list_by_billing_period(billing_period_name='201804-1', filter='usageEnd ge 2018-01-26T23:59:59Z') + pages = self.consumption_client.marketplaces.list_by_billing_period( + billing_period_name="201804-1", filter="usageEnd ge 2018-01-26T23:59:59Z" + ) first_page = pages.advance_page() output = list(first_page) self._validate_marketplace(output[0]) @recorded_by_proxy def test_consumption_billing_period_price_sheet(self): - output = self.consumption_client.price_sheet.get_by_billing_period(billing_period_name=MgmtConsumptionTest.billingPeriodName, expand='properties/meterDetails') + output = self.consumption_client.price_sheet.get_by_billing_period( + billing_period_name=MgmtConsumptionTest.billingPeriodName, expand="properties/meterDetails" + ) self._validate_price_sheet(output) @recorded_by_proxy def test_consumption_subscription_price_sheet_expand(self): - output = self.consumption_client.price_sheet.get(expand='properties/meterDetails') + output = self.consumption_client.price_sheet.get(expand="properties/meterDetails") self._validate_price_sheet(output) @recorded_by_proxy @@ -271,6 +348,7 @@ def test_consumption_subscription_price_sheet(self): output = self.consumption_client.price_sheet.get(top=1) self._validate_price_sheet(output, included_paging=True) -#------------------------------------------------------------------------------ -if __name__ == '__main__': + +# ------------------------------------------------------------------------------ +if __name__ == "__main__": unittest.main() diff --git a/sdk/consumption/azure-mgmt-consumption/tsp-location.yaml b/sdk/consumption/azure-mgmt-consumption/tsp-location.yaml new file mode 100644 index 000000000000..b403710bcd08 --- /dev/null +++ b/sdk/consumption/azure-mgmt-consumption/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/consumption/resource-manager/Microsoft.Consumption/Consumption +commit: aa9df243e9a6ecf6110383e079d622a87bd405d3 +repo: Azure/azure-rest-api-specs +additionalDirectories: