From 1e55a23affb9fdfde632f5c3be1462ea0056d997 Mon Sep 17 00:00:00 2001 From: azure-sdk Date: Thu, 28 May 2026 04:08:37 +0000 Subject: [PATCH 1/6] Configurations: 'specification/reservations/resource-manager/Microsoft.Capacity/Reservations/tspconfig.yaml', API Version: 2022-11-01, SDK Release Type: beta, and CommitSHA: 'cb62053a18882dd258d9922be9770702b7ef6ac9' in SpecRepo: 'https://github.com/Azure/azure-rest-api-specs' Pipeline run: https://dev.azure.com/azure-sdk/internal/_build/results?buildId=6362431 Refer to https://eng.ms/docs/products/azure-developer-experience/develop/sdk-release/sdk-release-prerequisites to prepare for SDK release. --- .../azure-mgmt-reservations/CHANGELOG.md | 73 + .../azure-mgmt-reservations/MANIFEST.in | 9 +- .../azure-mgmt-reservations/README.md | 14 +- .../azure-mgmt-reservations/_meta.json | 11 - .../azure-mgmt-reservations/_metadata.json | 10 + .../apiview-properties.json | 179 + .../azure-mgmt-reservations/azure/__init__.py | 2 +- .../azure/mgmt/__init__.py | 2 +- .../azure/mgmt/reservations/__init__.py | 16 +- .../{_azure_reservation_api.py => _client.py} | 119 +- .../azure/mgmt/reservations/_configuration.py | 32 +- .../azure/mgmt/reservations/_patch.py | 39 +- .../mgmt/reservations/_utils/__init__.py | 6 + .../mgmt/reservations/_utils/model_base.py | 1755 ++++++ .../serialization.py} | 728 +-- .../{aio/_vendor.py => _utils/utils.py} | 21 +- .../azure/mgmt/reservations/_validation.py | 66 + .../azure/mgmt/reservations/_vendor.py | 48 - .../azure/mgmt/reservations/_version.py | 4 +- .../azure/mgmt/reservations/aio/__init__.py | 16 +- .../{_azure_reservation_api.py => _client.py} | 125 +- .../mgmt/reservations/aio/_configuration.py | 32 +- .../azure/mgmt/reservations/aio/_patch.py | 39 +- .../reservations/aio/operations/__init__.py | 39 +- .../_azure_reservation_api_operations.py | 219 - .../_calculate_exchange_operations.py | 258 - .../_calculate_refund_operations.py | 181 - .../aio/operations/_exchange_operations.py | 258 - .../aio/operations/_operation_operations.py | 129 - .../aio/operations/_operations.py | 4321 ++++++++++++++ .../reservations/aio/operations/_patch.py | 12 +- .../aio/operations/_quota_operations.py | 793 --- .../_quota_request_status_operations.py | 238 - .../aio/operations/_reservation_operations.py | 1391 ----- .../_reservation_order_operations.py | 651 --- .../_return_operations_operations.py | 270 - .../mgmt/reservations/models/__init__.py | 287 +- ...ure_reservation_api_enums.py => _enums.py} | 227 +- .../azure/mgmt/reservations/models/_models.py | 4868 ++++++++++++++++ .../mgmt/reservations/models/_models_py3.py | 4902 ---------------- .../azure/mgmt/reservations/models/_patch.py | 12 +- .../mgmt/reservations/operations/__init__.py | 39 +- .../_azure_reservation_api_operations.py | 295 - .../_calculate_exchange_operations.py | 281 - .../_calculate_refund_operations.py | 212 - .../operations/_exchange_operations.py | 281 - .../operations/_operation_operations.py | 149 - .../reservations/operations/_operations.py | 5047 +++++++++++++++++ .../mgmt/reservations/operations/_patch.py | 12 +- .../operations/_quota_operations.py | 905 --- .../_quota_request_status_operations.py | 312 - .../operations/_reservation_operations.py | 1672 ------ .../_reservation_order_operations.py | 763 --- .../_return_operations_operations.py | 296 - .../generated_samples/archive.py | 12 +- .../generated_samples/calculate_exchange.py | 10 +- .../generated_samples/calculate_refund.py | 10 +- .../calculate_reservation_order.py | 9 +- .../change_directory_reservation_order.py | 9 +- .../generated_samples/exchange.py | 9 +- .../get_applied_reservations.py | 9 +- .../generated_samples/get_available_scope.py | 9 +- .../generated_samples/get_catalog.py | 9 +- .../get_compute_one_sku_usages.py | 9 +- .../generated_samples/get_compute_usages.py | 9 +- .../get_machine_learning_services_usages.py | 9 +- .../generated_samples/get_operations.py | 9 +- .../get_quota_request_status_by_id.py | 9 +- .../get_quota_request_status_failed.py | 9 +- .../get_quota_request_status_in_progress.py | 11 +- .../get_quota_requests_history.py | 9 +- .../get_reservation_details.py | 9 +- .../get_reservation_order_details.py | 9 +- ...er_details_with_expand_plan_information.py | 9 +- .../get_reservation_orders.py | 9 +- .../get_reservation_revisions.py | 9 +- .../generated_samples/get_reservations.py | 9 +- .../get_reservations_from_order.py | 9 +- .../generated_samples/merge_reservations.py | 10 +- .../patch_compute_quota_request.py | 9 +- .../purchase_reservation_order.py | 9 +- .../put_compute_one_sku_quota_request.py | 9 +- ...arning_services_quota_request_dedicated.py | 9 +- ...ing_services_quota_request_low_priority.py | 9 +- .../generated_samples/return.py | 10 +- .../generated_samples/split_reservation.py | 10 +- .../generated_samples/unarchive.py | 12 +- .../generated_samples/update_reservation.py | 9 +- .../generated_tests/conftest.py | 35 + .../generated_tests/test_reservations_mgmt.py | 41 + .../test_reservations_mgmt_async.py | 42 + ...ions_mgmt_calculate_exchange_operations.py | 80 + ...gmt_calculate_exchange_operations_async.py | 83 + ...ations_mgmt_calculate_refund_operations.py | 34 + ..._mgmt_calculate_refund_operations_async.py | 35 + ...t_reservations_mgmt_exchange_operations.py | 30 + ...rvations_mgmt_exchange_operations_async.py | 33 + ..._reservations_mgmt_operation_operations.py | 29 + ...vations_mgmt_operation_operations_async.py | 30 + ...test_reservations_mgmt_quota_operations.py | 118 + ...eservations_mgmt_quota_operations_async.py | 123 + ...ns_mgmt_quota_request_status_operations.py | 46 + ...t_quota_request_status_operations_async.py | 47 + ...eservations_mgmt_reservation_operations.py | 180 + ...tions_mgmt_reservation_operations_async.py | 189 + ...tions_mgmt_reservation_order_operations.py | 121 + ...mgmt_reservation_order_operations_async.py | 124 + ...est_reservations_mgmt_return_operations.py | 38 + ...servations_mgmt_return_operations_async.py | 41 + .../azure-mgmt-reservations/pyproject.toml | 81 + .../sdk_packaging.toml | 6 - .../azure-mgmt-reservations/setup.py | 79 - .../tests/test_mgmt_reservations.py | 72 +- .../azure-mgmt-reservations/tsp-location.yaml | 4 + 114 files changed, 19183 insertions(+), 15543 deletions(-) delete mode 100644 sdk/reservations/azure-mgmt-reservations/_meta.json create mode 100644 sdk/reservations/azure-mgmt-reservations/_metadata.json create mode 100644 sdk/reservations/azure-mgmt-reservations/apiview-properties.json rename sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/{_azure_reservation_api.py => _client.py} (58%) create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/__init__.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/model_base.py rename sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/{_serialization.py => _utils/serialization.py} (77%) rename sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/{aio/_vendor.py => _utils/utils.py} (53%) create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_validation.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py rename sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/{_azure_reservation_api.py => _client.py} (58%) delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py rename sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/{_azure_reservation_api_enums.py => _enums.py} (66%) create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models_py3.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/conftest.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations_async.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_operations.py create mode 100644 sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_operations_async.py delete mode 100644 sdk/reservations/azure-mgmt-reservations/sdk_packaging.toml delete mode 100644 sdk/reservations/azure-mgmt-reservations/setup.py create mode 100644 sdk/reservations/azure-mgmt-reservations/tsp-location.yaml diff --git a/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md b/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md index 5941af0fddbb..a53ababa5ae2 100644 --- a/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md +++ b/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md @@ -1,5 +1,78 @@ # Release History +## 3.0.0b1 (2026-05-28) + +### Features Added + + - Model `CurrentQuotaLimitBase` added property `system_data` + - Model `QuotaRequestDetails` added property `properties` + - Model `QuotaRequestDetails` added property `system_data` + - Model `ReservationOrderResponse` added property `properties` + - Model `SkuRestriction` added property `values_property` + - Added model `MergeProperties` + - Added model `PatchProperties` + - Added model `ReservationOrderProperties` + - Added model `SplitProperties` + +### Breaking Changes + + - Deleted or renamed model `AzureReservationAPI` + - Model `MergeRequest` deleted or renamed its instance variable `sources` + - Model `Patch` deleted or renamed its instance variable `applied_scope_type` + - Model `Patch` deleted or renamed its instance variable `applied_scopes` + - Model `Patch` deleted or renamed its instance variable `applied_scope_properties` + - Model `Patch` deleted or renamed its instance variable `instance_flexibility` + - Model `Patch` deleted or renamed its instance variable `name` + - Model `Patch` deleted or renamed its instance variable `renew` + - Model `Patch` deleted or renamed its instance variable `renew_properties` + - Model `Patch` deleted or renamed its instance variable `review_date_time` + - Model `QuotaRequestDetails` deleted or renamed its instance variable `provisioning_state` + - Model `QuotaRequestDetails` deleted or renamed its instance variable `message` + - Model `QuotaRequestDetails` deleted or renamed its instance variable `request_submit_time` + - Model `QuotaRequestDetails` deleted or renamed its instance variable `value` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `display_name` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `request_date_time` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `created_date_time` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `expiry_date` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `expiry_date_time` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `benefit_start_time` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `original_quantity` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `term` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `provisioning_state` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `billing_plan` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `plan_information` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `reservations` + - Model `ReservationOrderResponse` deleted or renamed its instance variable `review_date_time` + - Model `SkuRestriction` deleted or renamed its instance variable `values` + - Model `SplitRequest` deleted or renamed its instance variable `quantities` + - Model `SplitRequest` deleted or renamed its instance variable `reservation_id` + - Deleted or renamed model `CatalogsResult` + - Deleted or renamed model `CreateGenericQuotaRequestParameters` + - Deleted or renamed model `CurrentQuotaLimit` + - Deleted or renamed model `DisplayProvisioningState` + - Deleted or renamed model `Location` + - Deleted or renamed model `OperationList` + - Deleted or renamed model `QuotaLimits` + - Deleted or renamed model `QuotaLimitsResponse` + - Deleted or renamed model `QuotaRequestDetailsList` + - Deleted or renamed model `QuotaRequestOneResourceSubmitResponse` + - Deleted or renamed model `QuotaRequestSubmitResponse` + - Deleted or renamed model `QuotaRequestSubmitResponse201` + - Deleted or renamed model `RefundResponse` + - Deleted or renamed model `ReservationList` + - Deleted or renamed model `ReservationOrderList` + - Deleted or renamed model `UserFriendlyAppliedScopeType` + - Deleted or renamed model `UserFriendlyRenewState` + - Method `QuotaRequestStatusOperations.list` changed its parameter `skiptoken` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOperations.get` changed its parameter `expand` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOperations.list_all` changed its parameter `orderby` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOperations.list_all` changed its parameter `refresh_summary` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOperations.list_all` changed its parameter `skiptoken` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOperations.list_all` changed its parameter `selected_state` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOperations.list_all` changed its parameter `take` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOrderOperations.get` changed its parameter `expand` from `positional_or_keyword` to `keyword_only` + - Deleted or renamed model `AzureReservationAPIOperationsMixin` + ## 2.3.0 (2023-03-20) ### Features Added diff --git a/sdk/reservations/azure-mgmt-reservations/MANIFEST.in b/sdk/reservations/azure-mgmt-reservations/MANIFEST.in index 19d02d6aa0b2..35c65c2b4cce 100644 --- a/sdk/reservations/azure-mgmt-reservations/MANIFEST.in +++ b/sdk/reservations/azure-mgmt-reservations/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/reservations/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py diff --git a/sdk/reservations/azure-mgmt-reservations/README.md b/sdk/reservations/azure-mgmt-reservations/README.md index 636b6f62c449..77964ccbdf70 100644 --- a/sdk/reservations/azure-mgmt-reservations/README.md +++ b/sdk/reservations/azure-mgmt-reservations/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Reservations 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_ @@ -12,7 +12,7 @@ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For ### Prerequisites -- Python 3.7+ is required to use this package. +- Python 3.10+ is required to use this package. - [Azure subscription](https://azure.microsoft.com/free/) ### Install the package @@ -24,7 +24,7 @@ pip install azure-identity ### Authentication -By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configure of following environment variables. +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. @@ -45,8 +45,9 @@ client = AzureReservationAPI(credential=DefaultAzureCredential(), subscription_i ## Examples - -Code samples for this package can be found at [Reservations](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com and [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) +Code samples for this package can be found at: +- [Search Reservations](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 @@ -58,6 +59,3 @@ Code samples for this package can be found at [Reservations](https://docs.micros 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/reservations/azure-mgmt-reservations/_meta.json b/sdk/reservations/azure-mgmt-reservations/_meta.json deleted file mode 100644 index e46ad70853d9..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "66174681c09b101de03fd35399080cfbccc93e8f", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", - "use": [ - "@autorest/python@6.4.0", - "@autorest/modelerfour@4.24.3" - ], - "autorest_command": "autorest specification/reservations/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.4.0 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", - "readme": "specification/reservations/resource-manager/readme.md" -} \ No newline at end of file diff --git a/sdk/reservations/azure-mgmt-reservations/_metadata.json b/sdk/reservations/azure-mgmt-reservations/_metadata.json new file mode 100644 index 000000000000..6e60dd37bfa7 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/_metadata.json @@ -0,0 +1,10 @@ +{ + "apiVersions": { + "Quota": "2020-10-25", + "Reservations": "2022-11-01" + }, + "commit": "cb62053a18882dd258d9922be9770702b7ef6ac9", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/reservations/resource-manager/Microsoft.Capacity/Reservations", + "emitterVersion": "0.62.1" +} \ No newline at end of file diff --git a/sdk/reservations/azure-mgmt-reservations/apiview-properties.json b/sdk/reservations/azure-mgmt-reservations/apiview-properties.json new file mode 100644 index 000000000000..9db4816ff1d8 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/apiview-properties.json @@ -0,0 +1,179 @@ +{ + "CrossLanguagePackageId": "Quota", + "CrossLanguageDefinitionId": { + "azure.mgmt.reservations.models.AppliedReservationList": "Reservations.AppliedReservationList", + "azure.mgmt.reservations.models.AppliedReservations": "Reservations.AppliedReservations", + "azure.mgmt.reservations.models.AppliedReservationsProperties": "Reservations.AppliedReservationsProperties", + "azure.mgmt.reservations.models.AppliedScopeProperties": "Reservations.AppliedScopeProperties", + "azure.mgmt.reservations.models.AvailableScopeProperties": "Reservations.AvailableScopeProperties", + "azure.mgmt.reservations.models.AvailableScopeRequest": "Reservations.AvailableScopeRequest", + "azure.mgmt.reservations.models.AvailableScopeRequestProperties": "Reservations.AvailableScopeRequestProperties", + "azure.mgmt.reservations.models.BillingInformation": "Reservations.BillingInformation", + "azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse": "Reservations.CalculateExchangeOperationResultResponse", + "azure.mgmt.reservations.models.CalculateExchangeRequest": "Reservations.CalculateExchangeRequest", + "azure.mgmt.reservations.models.CalculateExchangeRequestProperties": "Reservations.CalculateExchangeRequestProperties", + "azure.mgmt.reservations.models.CalculateExchangeResponseProperties": "Reservations.CalculateExchangeResponseProperties", + "azure.mgmt.reservations.models.CalculatePriceResponse": "Reservations.CalculatePriceResponse", + "azure.mgmt.reservations.models.CalculatePriceResponseProperties": "Reservations.CalculatePriceResponseProperties", + "azure.mgmt.reservations.models.CalculatePriceResponsePropertiesBillingCurrencyTotal": "Reservations.CalculatePriceResponsePropertiesBillingCurrencyTotal", + "azure.mgmt.reservations.models.CalculatePriceResponsePropertiesPricingCurrencyTotal": "Reservations.CalculatePriceResponsePropertiesPricingCurrencyTotal", + "azure.mgmt.reservations.models.CalculateRefundRequest": "Reservations.CalculateRefundRequest", + "azure.mgmt.reservations.models.CalculateRefundRequestProperties": "Reservations.CalculateRefundRequestProperties", + "azure.mgmt.reservations.models.CalculateRefundResponse": "Reservations.CalculateRefundResponse", + "azure.mgmt.reservations.models.Catalog": "Reservations.Catalog", + "azure.mgmt.reservations.models.CatalogMsrp": "Reservations.CatalogMsrp", + "azure.mgmt.reservations.models.ChangeDirectoryRequest": "Reservations.ChangeDirectoryRequest", + "azure.mgmt.reservations.models.ChangeDirectoryResponse": "Reservations.ChangeDirectoryResponse", + "azure.mgmt.reservations.models.ChangeDirectoryResult": "Reservations.ChangeDirectoryResult", + "azure.mgmt.reservations.models.Price": "Reservations.Price", + "azure.mgmt.reservations.models.Commitment": "Reservations.Commitment", + "azure.mgmt.reservations.models.Resource": "Azure.ResourceManager.CommonTypes.Resource", + "azure.mgmt.reservations.models.ProxyResource": "Azure.ResourceManager.CommonTypes.ProxyResource", + "azure.mgmt.reservations.models.CurrentQuotaLimitBase": "Quota.CurrentQuotaLimitBase", + "azure.mgmt.reservations.models.Error": "Reservations.Error", + "azure.mgmt.reservations.models.ErrorDetails": "Reservations.ErrorDetails", + "azure.mgmt.reservations.models.ErrorResponse": "Reservations.ErrorResponse", + "azure.mgmt.reservations.models.ExceptionResponse": "Quota.ExceptionResponse", + "azure.mgmt.reservations.models.ExchangeOperationResultResponse": "Reservations.ExchangeOperationResultResponse", + "azure.mgmt.reservations.models.ExchangePolicyError": "Reservations.ExchangePolicyError", + "azure.mgmt.reservations.models.ExchangePolicyErrors": "Reservations.ExchangePolicyErrors", + "azure.mgmt.reservations.models.ExchangeRequest": "Reservations.ExchangeRequest", + "azure.mgmt.reservations.models.ExchangeRequestProperties": "Reservations.ExchangeRequestProperties", + "azure.mgmt.reservations.models.ExchangeResponseProperties": "Reservations.ExchangeResponseProperties", + "azure.mgmt.reservations.models.ExtendedErrorInfo": "Reservations.ExtendedErrorInfo", + "azure.mgmt.reservations.models.ExtendedStatusInfo": "Reservations.ExtendedStatusInfo", + "azure.mgmt.reservations.models.MergeProperties": "Reservations.MergeProperties", + "azure.mgmt.reservations.models.MergeRequest": "Reservations.MergeRequest", + "azure.mgmt.reservations.models.OperationDisplay": "Reservations.OperationDisplay", + "azure.mgmt.reservations.models.OperationResponse": "Reservations.OperationResponse", + "azure.mgmt.reservations.models.OperationResultError": "Reservations.OperationResultError", + "azure.mgmt.reservations.models.Patch": "Reservations.Patch", + "azure.mgmt.reservations.models.PatchProperties": "Reservations.PatchProperties", + "azure.mgmt.reservations.models.PatchPropertiesRenewProperties": "Reservations.PatchPropertiesRenewProperties", + "azure.mgmt.reservations.models.PaymentDetail": "Reservations.PaymentDetail", + "azure.mgmt.reservations.models.PurchaseRequest": "Reservations.PurchaseRequest", + "azure.mgmt.reservations.models.PurchaseRequestProperties": "Reservations.PurchaseRequestProperties", + "azure.mgmt.reservations.models.PurchaseRequestPropertiesReservedResourceProperties": "Reservations.PurchaseRequestPropertiesReservedResourceProperties", + "azure.mgmt.reservations.models.QuotaProperties": "Quota.QuotaProperties", + "azure.mgmt.reservations.models.QuotaRequestDetails": "Quota.QuotaRequestDetails", + "azure.mgmt.reservations.models.QuotaRequestProperties": "Quota.QuotaRequestProperties", + "azure.mgmt.reservations.models.RefundBillingInformation": "Reservations.RefundBillingInformation", + "azure.mgmt.reservations.models.RefundPolicyError": "Reservations.RefundPolicyError", + "azure.mgmt.reservations.models.RefundPolicyResult": "Reservations.RefundPolicyResult", + "azure.mgmt.reservations.models.RefundPolicyResultProperty": "Reservations.RefundPolicyResultProperty", + "azure.mgmt.reservations.models.RefundRequest": "Reservations.RefundRequest", + "azure.mgmt.reservations.models.RefundRequestProperties": "Reservations.RefundRequestProperties", + "azure.mgmt.reservations.models.RefundResponseProperties": "Reservations.RefundResponseProperties", + "azure.mgmt.reservations.models.RenewPropertiesResponse": "Reservations.RenewPropertiesResponse", + "azure.mgmt.reservations.models.RenewPropertiesResponseBillingCurrencyTotal": "Reservations.RenewPropertiesResponseBillingCurrencyTotal", + "azure.mgmt.reservations.models.RenewPropertiesResponsePricingCurrencyTotal": "Reservations.RenewPropertiesResponsePricingCurrencyTotal", + "azure.mgmt.reservations.models.ReservationMergeProperties": "Reservations.ReservationMergeProperties", + "azure.mgmt.reservations.models.ReservationOrderBillingPlanInformation": "Reservations.ReservationOrderBillingPlanInformation", + "azure.mgmt.reservations.models.ReservationOrderProperties": "Reservations.ReservationOrderProperties", + "azure.mgmt.reservations.models.ReservationOrderResponse": "Reservations.ReservationOrderResponse", + "azure.mgmt.reservations.models.ReservationResponse": "Reservations.ReservationResponse", + "azure.mgmt.reservations.models.ReservationSplitProperties": "Reservations.ReservationSplitProperties", + "azure.mgmt.reservations.models.ReservationsProperties": "Reservations.ReservationsProperties", + "azure.mgmt.reservations.models.ReservationsPropertiesUtilization": "Reservations.ReservationsPropertiesUtilization", + "azure.mgmt.reservations.models.ReservationSummary": "Reservations.ReservationSummary", + "azure.mgmt.reservations.models.ReservationSwapProperties": "Reservations.ReservationSwapProperties", + "azure.mgmt.reservations.models.ReservationToExchange": "Reservations.ReservationToExchange", + "azure.mgmt.reservations.models.ReservationToPurchaseCalculateExchange": "Reservations.ReservationToPurchaseCalculateExchange", + "azure.mgmt.reservations.models.ReservationToPurchaseExchange": "Reservations.ReservationToPurchaseExchange", + "azure.mgmt.reservations.models.ReservationToReturn": "Reservations.ReservationToReturn", + "azure.mgmt.reservations.models.ReservationToReturnForExchange": "Reservations.ReservationToReturnForExchange", + "azure.mgmt.reservations.models.ReservationUtilizationAggregates": "Reservations.ReservationUtilizationAggregates", + "azure.mgmt.reservations.models.ResourceName": "Quota.ResourceName", + "azure.mgmt.reservations.models.SavingsPlanPurchaseRequest": "Reservations.SavingsPlanPurchaseRequest", + "azure.mgmt.reservations.models.SavingsPlanPurchaseRequestProperties": "Reservations.SavingsPlanPurchaseRequestProperties", + "azure.mgmt.reservations.models.SavingsPlanToPurchaseCalculateExchange": "Reservations.SavingsPlanToPurchaseCalculateExchange", + "azure.mgmt.reservations.models.SavingsPlanToPurchaseExchange": "Reservations.SavingsPlanToPurchaseExchange", + "azure.mgmt.reservations.models.ScopeProperties": "Reservations.ScopeProperties", + "azure.mgmt.reservations.models.ServiceError": "Quota.ServiceError", + "azure.mgmt.reservations.models.ServiceErrorDetail": "Quota.ServiceErrorDetail", + "azure.mgmt.reservations.models.SkuCapability": "Reservations.SkuCapability", + "azure.mgmt.reservations.models.SkuName": "Reservations.SkuName", + "azure.mgmt.reservations.models.SkuProperty": "Reservations.SkuProperty", + "azure.mgmt.reservations.models.SkuRestriction": "Reservations.SkuRestriction", + "azure.mgmt.reservations.models.SplitProperties": "Reservations.SplitProperties", + "azure.mgmt.reservations.models.SplitRequest": "Reservations.SplitRequest", + "azure.mgmt.reservations.models.SubRequest": "Quota.SubRequest", + "azure.mgmt.reservations.models.SubscriptionScopeProperties": "Reservations.SubscriptionScopeProperties", + "azure.mgmt.reservations.models.SystemData": "Azure.ResourceManager.CommonTypes.SystemData", + "azure.mgmt.reservations.models.CreatedByType": "Azure.ResourceManager.CommonTypes.createdByType", + "azure.mgmt.reservations.models.QuotaRequestState": "Quota.QuotaRequestState", + "azure.mgmt.reservations.models.ErrorResponseCode": "Reservations.ErrorResponseCode", + "azure.mgmt.reservations.models.ResourceType": "Quota.ResourceType", + "azure.mgmt.reservations.models.ReservedResourceType": "Reservations.ReservedResourceType", + "azure.mgmt.reservations.models.InstanceFlexibility": "Reservations.InstanceFlexibility", + "azure.mgmt.reservations.models.AppliedScopeType": "Reservations.AppliedScopeType", + "azure.mgmt.reservations.models.ProvisioningState": "Reservations.ProvisioningState", + "azure.mgmt.reservations.models.ReservationStatusCode": "Reservations.ReservationStatusCode", + "azure.mgmt.reservations.models.ReservationBillingPlan": "Reservations.ReservationBillingPlan", + "azure.mgmt.reservations.models.ReservationTerm": "Reservations.ReservationTerm", + "azure.mgmt.reservations.models.PaymentStatus": "Reservations.PaymentStatus", + "azure.mgmt.reservations.models.CalculateExchangeOperationResultStatus": "Reservations.CalculateExchangeOperationResultStatus", + "azure.mgmt.reservations.models.SavingsPlanTerm": "Reservations.SavingsPlanTerm", + "azure.mgmt.reservations.models.BillingPlan": "Reservations.BillingPlan", + "azure.mgmt.reservations.models.CommitmentGrain": "Reservations.CommitmentGrain", + "azure.mgmt.reservations.models.ExchangeOperationResultStatus": "Reservations.ExchangeOperationResultStatus", + "azure.mgmt.reservations.models.OperationStatus": "Reservations.OperationStatus", + "azure.mgmt.reservations.operations.QuotaRequestStatusOperations.get": "Quota.QuotaRequestStatus.get", + "azure.mgmt.reservations.aio.operations.QuotaRequestStatusOperations.get": "Quota.QuotaRequestStatus.get", + "azure.mgmt.reservations.operations.QuotaRequestStatusOperations.list": "Quota.QuotaRequestStatus.list", + "azure.mgmt.reservations.aio.operations.QuotaRequestStatusOperations.list": "Quota.QuotaRequestStatus.list", + "azure.mgmt.reservations.operations.OperationOperations.list": "Reservations.Operation.list", + "azure.mgmt.reservations.aio.operations.OperationOperations.list": "Reservations.Operation.list", + "azure.mgmt.reservations.operations.QuotaOperations.get": "Quota.CurrentQuotaLimitBases.get", + "azure.mgmt.reservations.aio.operations.QuotaOperations.get": "Quota.CurrentQuotaLimitBases.get", + "azure.mgmt.reservations.operations.QuotaOperations.begin_create_or_update": "Quota.CurrentQuotaLimitBases.createOrUpdate", + "azure.mgmt.reservations.aio.operations.QuotaOperations.begin_create_or_update": "Quota.CurrentQuotaLimitBases.createOrUpdate", + "azure.mgmt.reservations.operations.QuotaOperations.begin_update": "Quota.CurrentQuotaLimitBases.update", + "azure.mgmt.reservations.aio.operations.QuotaOperations.begin_update": "Quota.CurrentQuotaLimitBases.update", + "azure.mgmt.reservations.operations.QuotaOperations.list": "Quota.CurrentQuotaLimitBases.list", + "azure.mgmt.reservations.aio.operations.QuotaOperations.list": "Quota.CurrentQuotaLimitBases.list", + "azure.mgmt.reservations.operations.ReservationOperations.get": "Reservations.ReservationResponses.get", + "azure.mgmt.reservations.aio.operations.ReservationOperations.get": "Reservations.ReservationResponses.get", + "azure.mgmt.reservations.operations.ReservationOperations.begin_update": "Reservations.ReservationResponses.update", + "azure.mgmt.reservations.aio.operations.ReservationOperations.begin_update": "Reservations.ReservationResponses.update", + "azure.mgmt.reservations.operations.ReservationOperations.list": "Reservations.ReservationResponses.list", + "azure.mgmt.reservations.aio.operations.ReservationOperations.list": "Reservations.ReservationResponses.list", + "azure.mgmt.reservations.operations.ReservationOperations.begin_available_scopes": "Reservations.ReservationResponses.availableScopes", + "azure.mgmt.reservations.aio.operations.ReservationOperations.begin_available_scopes": "Reservations.ReservationResponses.availableScopes", + "azure.mgmt.reservations.operations.ReservationOperations.archive": "Reservations.ReservationResponses.archive", + "azure.mgmt.reservations.aio.operations.ReservationOperations.archive": "Reservations.ReservationResponses.archive", + "azure.mgmt.reservations.operations.ReservationOperations.unarchive": "Reservations.ReservationResponses.unarchive", + "azure.mgmt.reservations.aio.operations.ReservationOperations.unarchive": "Reservations.ReservationResponses.unarchive", + "azure.mgmt.reservations.operations.ReservationOperations.list_revisions": "Reservations.ReservationResponses.listRevisions", + "azure.mgmt.reservations.aio.operations.ReservationOperations.list_revisions": "Reservations.ReservationResponses.listRevisions", + "azure.mgmt.reservations.operations.ReservationOperations.begin_split": "Reservations.ReservationOrderResponses.split", + "azure.mgmt.reservations.aio.operations.ReservationOperations.begin_split": "Reservations.ReservationOrderResponses.split", + "azure.mgmt.reservations.operations.ReservationOperations.begin_merge": "Reservations.ReservationOrderResponses.merge", + "azure.mgmt.reservations.aio.operations.ReservationOperations.begin_merge": "Reservations.ReservationOrderResponses.merge", + "azure.mgmt.reservations.operations.ReservationOperations.list_all": "Reservations.ReservationOperationGroup.listAll", + "azure.mgmt.reservations.aio.operations.ReservationOperations.list_all": "Reservations.ReservationOperationGroup.listAll", + "azure.mgmt.reservations.operations.ReservationOrderOperations.get": "Reservations.ReservationOrderResponses.get", + "azure.mgmt.reservations.aio.operations.ReservationOrderOperations.get": "Reservations.ReservationOrderResponses.get", + "azure.mgmt.reservations.operations.ReservationOrderOperations.begin_purchase": "Reservations.ReservationOrderResponses.purchase", + "azure.mgmt.reservations.aio.operations.ReservationOrderOperations.begin_purchase": "Reservations.ReservationOrderResponses.purchase", + "azure.mgmt.reservations.operations.ReservationOrderOperations.list": "Reservations.ReservationOrderResponses.list", + "azure.mgmt.reservations.aio.operations.ReservationOrderOperations.list": "Reservations.ReservationOrderResponses.list", + "azure.mgmt.reservations.operations.ReservationOrderOperations.change_directory": "Reservations.ReservationOrderResponses.changeDirectory", + "azure.mgmt.reservations.aio.operations.ReservationOrderOperations.change_directory": "Reservations.ReservationOrderResponses.changeDirectory", + "azure.mgmt.reservations.operations.ReservationOrderOperations.calculate": "Reservations.ReservationOrderOperationGroup.calculate", + "azure.mgmt.reservations.aio.operations.ReservationOrderOperations.calculate": "Reservations.ReservationOrderOperationGroup.calculate", + "azure.mgmt.reservations.operations.CalculateRefundOperations.post": "Reservations.ReservationOrderResponses.post", + "azure.mgmt.reservations.aio.operations.CalculateRefundOperations.post": "Reservations.ReservationOrderResponses.post", + "azure.mgmt.reservations.operations.ReturnOperations.begin_post": "Reservations.ReservationOrderResponses.returnPost", + "azure.mgmt.reservations.aio.operations.ReturnOperations.begin_post": "Reservations.ReservationOrderResponses.returnPost", + "azure.mgmt.reservations.operations.CalculateExchangeOperations.begin_post": "Reservations.CalculateExchangeOperationGroup.post", + "azure.mgmt.reservations.aio.operations.CalculateExchangeOperations.begin_post": "Reservations.CalculateExchangeOperationGroup.post", + "azure.mgmt.reservations.operations.ExchangeOperations.begin_post": "Reservations.ExchangeOperationGroup.post", + "azure.mgmt.reservations.aio.operations.ExchangeOperations.begin_post": "Reservations.ExchangeOperationGroup.post", + "azure.mgmt.reservations.ReservationsMgmtClient.get_catalog": "Reservations.getCatalog", + "azure.mgmt.reservations.aio.ReservationsMgmtClient.get_catalog": "Reservations.getCatalog", + "azure.mgmt.reservations.ReservationsMgmtClient.get_applied_reservation_list": "Reservations.getAppliedReservationList", + "azure.mgmt.reservations.aio.ReservationsMgmtClient.get_applied_reservation_list": "Reservations.getAppliedReservationList" + }, + "CrossLanguageVersion": "f97e7ee88162" +} \ No newline at end of file diff --git a/sdk/reservations/azure-mgmt-reservations/azure/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py index d175ae48b42c..988336bf41f7 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/__init__.py @@ -2,25 +2,31 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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 ._azure_reservation_api import AzureReservationAPI +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ReservationsMgmtClient # 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 __all__ = [ - "AzureReservationAPI", + "ReservationsMgmtClient", ] -__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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_azure_reservation_api.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_client.py similarity index 58% rename from sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_azure_reservation_api.py rename to sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_client.py index 11e00f688033..e75231611852 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_azure_reservation_api.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_client.py @@ -2,21 +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. # -------------------------------------------------------------------------- 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 AzureReservationAPIConfiguration -from ._serialization import Deserializer, Serializer +from ._configuration import ReservationsMgmtClientConfiguration +from ._utils.serialization import Deserializer, Serializer from .operations import ( - AzureReservationAPIOperationsMixin, CalculateExchangeOperations, CalculateRefundOperations, ExchangeOperations, @@ -26,24 +29,34 @@ ReservationOperations, ReservationOrderOperations, ReturnOperations, + _ReservationsMgmtClientOperationsMixin, ) +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 AzureReservationAPI( - AzureReservationAPIOperationsMixin +class ReservationsMgmtClient( + _ReservationsMgmtClientOperationsMixin ): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - """This API describe Azure Reservation. + """ReservationsMgmtClient. + :ivar quota_request_status: QuotaRequestStatusOperations operations + :vartype quota_request_status: azure.mgmt.reservations.operations.QuotaRequestStatusOperations + :ivar operation: OperationOperations operations + :vartype operation: azure.mgmt.reservations.operations.OperationOperations + :ivar quota: QuotaOperations operations + :vartype quota: azure.mgmt.reservations.operations.QuotaOperations :ivar reservation: ReservationOperations operations :vartype reservation: azure.mgmt.reservations.operations.ReservationOperations :ivar reservation_order: ReservationOrderOperations operations :vartype reservation_order: azure.mgmt.reservations.operations.ReservationOrderOperations - :ivar operation: OperationOperations operations - :vartype operation: azure.mgmt.reservations.operations.OperationOperations :ivar calculate_refund: CalculateRefundOperations operations :vartype calculate_refund: azure.mgmt.reservations.operations.CalculateRefundOperations :ivar return_operations: ReturnOperations operations @@ -52,33 +65,71 @@ class AzureReservationAPI( :vartype calculate_exchange: azure.mgmt.reservations.operations.CalculateExchangeOperations :ivar exchange: ExchangeOperations operations :vartype exchange: azure.mgmt.reservations.operations.ExchangeOperations - :ivar quota: QuotaOperations operations - :vartype quota: azure.mgmt.reservations.operations.QuotaOperations - :ivar quota_request_status: QuotaRequestStatusOperations operations - :vartype quota_request_status: azure.mgmt.reservations.operations.QuotaRequestStatusOperations - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :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 cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds :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", base_url: str = "https://management.azure.com", **kwargs: Any + self, + credential: "TokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any ) -> None: - self._config = AzureReservationAPIConfiguration(credential=credential, **kwargs) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _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 = ReservationsMgmtClientConfiguration( + credential=credential, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **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.quota_request_status = QuotaRequestStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) + self.quota = QuotaOperations(self._client, self._config, self._serialize, self._deserialize) self.reservation = ReservationOperations(self._client, self._config, self._serialize, self._deserialize) self.reservation_order = ReservationOrderOperations( self._client, self._config, self._serialize, self._deserialize ) - self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) self.calculate_refund = CalculateRefundOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -87,18 +138,14 @@ def __init__( self._client, self._config, self._serialize, self._deserialize ) self.exchange = ExchangeOperations(self._client, self._config, self._serialize, self._deserialize) - self.quota = QuotaOperations(self._client, self._config, self._serialize, self._deserialize) - self.quota_request_status = QuotaRequestStatusOperations( - self._client, self._config, self._serialize, self._deserialize - ) - 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 @@ -111,13 +158,17 @@ 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) -> "AzureReservationAPI": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py index 171468330d1e..f0150147014c 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_configuration.py @@ -2,41 +2,53 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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 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 TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials import TokenCredential -class AzureReservationAPIConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AzureReservationAPI. +class ReservationsMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ReservationsMgmtClient. 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 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 """ - def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(AzureReservationAPIConfiguration, self).__init__(**kwargs) + def __init__( + self, + credential: "TokenCredential", + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential + self.base_url = base_url + self.cloud_setting = cloud_setting self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-reservations/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -45,9 +57,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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_patch.py index f99e77fef986..ea765788358a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_patch.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/model_base.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/model_base.py new file mode 100644 index 000000000000..bd5b9caf1022 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_serialization.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/serialization.py similarity index 77% rename from sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_serialization.py rename to sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/serialization.py index f17c068e833e..a088671e9c51 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_serialization.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_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 @@ -39,7 +21,6 @@ import sys import codecs from typing import ( - Dict, Any, cast, Optional, @@ -48,11 +29,7 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, - List, - Mapping, ) try: @@ -63,12 +40,16 @@ import isodate # type: ignore -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -91,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 @@ -112,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: @@ -124,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 @@ -143,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 @@ -153,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 @@ -170,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: @@ -184,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: Dict[str, Any] = {} - for k in kwargs: + 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): @@ -305,13 +246,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """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: Any) -> bool: - """Compare objects by comparing all attributes.""" + """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) -> str: @@ -331,7 +282,11 @@ def is_xml_model(cls) -> bool: @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: @@ -340,7 +295,7 @@ 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: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """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)`. @@ -351,12 +306,14 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :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: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: """Return a dict that can be serialized using json.dump. @@ -385,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): @@ -400,30 +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: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + 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: Type[ModelType], + cls, data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -431,9 +392,11 @@ def from_dict( 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 = ( # type: ignore @@ -445,7 +408,7 @@ def from_dict( 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): @@ -453,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: @@ -506,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"} @@ -545,7 +514,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -561,17 +530,20 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = 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) @@ -597,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: @@ -629,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): @@ -638,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 @@ -649,7 +624,7 @@ 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 @@ -662,23 +637,24 @@ 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 @@ -707,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) @@ -729,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) @@ -762,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]"]: @@ -783,37 +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 AzureCoreNull: + 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) @@ -823,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 @@ -844,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 @@ -874,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. @@ -885,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.") @@ -903,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) @@ -941,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: @@ -965,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 @@ -973,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 @@ -983,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) @@ -997,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: @@ -1028,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) @@ -1085,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) @@ -1099,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], @@ -1135,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) @@ -1160,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 @@ -1180,17 +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: # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(List[str], _FLATTEN.split(key)) + dict_keys = cast(list[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1199,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 @@ -1220,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:]) @@ -1228,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) @@ -1271,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 @@ -1295,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): @@ -1327,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: @@ -1350,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. @@ -1359,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: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1381,7 +1395,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = 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 @@ -1391,33 +1405,56 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = 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) @@ -1434,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"... @@ -1471,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: @@ -1501,18 +1537,20 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :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__ # type: ignore @@ -1527,10 +1565,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :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 ) @@ -1548,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", {}) @@ -1568,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(): @@ -1601,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 @@ -1623,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) @@ -1642,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: @@ -1667,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): @@ -1677,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: @@ -1716,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 @@ -1728,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 @@ -1739,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): @@ -1764,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, @@ -1777,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): @@ -1790,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: @@ -1798,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: @@ -1819,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 @@ -1831,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 @@ -1846,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 @@ -1874,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 @@ -1883,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 @@ -1921,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 @@ -1972,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): @@ -1982,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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_vendor.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/utils.py similarity index 53% rename from sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_vendor.py rename to sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/utils.py index 40f39b95062c..35c9c836f85f 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_vendor.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_utils/utils.py @@ -1,28 +1,25 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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 abc import ABC -from typing import TYPE_CHECKING - -from azure.core.pipeline.transport import HttpRequest - -from ._configuration import AzureReservationAPIConfiguration +from typing import Generic, TYPE_CHECKING, TypeVar if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import AsyncPipelineClient + from .serialization import Deserializer, Serializer + - from .._serialization import Deserializer, Serializer +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") -class AzureReservationAPIMixinABC(ABC): +class ClientMixinABC(ABC, Generic[TClient, TConfig]): """DO NOT use this class. It is for internal typing use only.""" - _client: "AsyncPipelineClient" - _config: AzureReservationAPIConfiguration + _client: TClient + _config: TConfig _serialize: "Serializer" _deserialize: "Deserializer" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_validation.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_validation.py new file mode 100644 index 000000000000..f5af3a4eb8a2 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_validation.py @@ -0,0 +1,66 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft 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 functools + + +def api_version_validation(**kwargs): + params_added_on = kwargs.pop("params_added_on", {}) + method_added_on = kwargs.pop("method_added_on", "") + api_versions_list = kwargs.pop("api_versions_list", []) + + def _index_with_default(value: str, default: int = -1) -> int: + """Get the index of value in lst, or return default if not found. + + :param value: The value to search for in the api_versions_list. + :type value: str + :param default: The default value to return if the value is not found. + :type default: int + :return: The index of the value in the list, or the default value if not found. + :rtype: int + """ + try: + return api_versions_list.index(value) + except ValueError: + return default + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + # this assumes the client has an _api_version attribute + client = args[0] + client_api_version = client._config.api_version # pylint: disable=protected-access + except AttributeError: + return func(*args, **kwargs) + + if _index_with_default(method_added_on) > _index_with_default(client_api_version): + raise ValueError( + f"'{func.__name__}' is not available in API version " + f"{client_api_version}. Pass service API version {method_added_on} or newer to your client." + ) + + unsupported = { + parameter: api_version + for api_version, parameters in params_added_on.items() + for parameter in parameters + if parameter in kwargs and _index_with_default(api_version) > _index_with_default(client_api_version) + } + if unsupported: + raise ValueError( + "".join( + [ + f"'{param}' is not available in API version {client_api_version}. " + f"Use service API version {version} or newer.\n" + for param, version in unsupported.items() + ] + ) + ) + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py deleted file mode 100644 index 9123ccb875bc..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_vendor.py +++ /dev/null @@ -1,48 +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 abc import ABC -from typing import List, TYPE_CHECKING, cast - -from azure.core.pipeline.transport import HttpRequest - -from ._configuration import AzureReservationAPIConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import PipelineClient - - from ._serialization import Deserializer, Serializer - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - 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: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) - - -class AzureReservationAPIMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "PipelineClient" - _config: AzureReservationAPIConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_version.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_version.py index 6398307550c1..fd5e9189cf06 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_version.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/_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 = "2.3.0" +VERSION = "3.0.0b1" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py index 6f78ca5946b4..8614a46307df 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/__init__.py @@ -2,22 +2,28 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# 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 ._azure_reservation_api import AzureReservationAPI +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ReservationsMgmtClient # 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 __all__ = [ - "AzureReservationAPI", + "ReservationsMgmtClient", ] -__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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_azure_reservation_api.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_client.py similarity index 58% rename from sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_azure_reservation_api.py rename to sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_client.py index ec56c97be48e..c7105dfc2db1 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_azure_reservation_api.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_client.py @@ -2,21 +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. # -------------------------------------------------------------------------- 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 ._configuration import AzureReservationAPIConfiguration +from .._utils.serialization import Deserializer, Serializer +from ._configuration import ReservationsMgmtClientConfiguration from .operations import ( - AzureReservationAPIOperationsMixin, CalculateExchangeOperations, CalculateRefundOperations, ExchangeOperations, @@ -26,24 +29,35 @@ ReservationOperations, ReservationOrderOperations, ReturnOperations, + _ReservationsMgmtClientOperationsMixin, ) +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 AzureReservationAPI( - AzureReservationAPIOperationsMixin +class ReservationsMgmtClient( + _ReservationsMgmtClientOperationsMixin ): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - """This API describe Azure Reservation. + """ReservationsMgmtClient. + :ivar quota_request_status: QuotaRequestStatusOperations operations + :vartype quota_request_status: + azure.mgmt.reservations.aio.operations.QuotaRequestStatusOperations + :ivar operation: OperationOperations operations + :vartype operation: azure.mgmt.reservations.aio.operations.OperationOperations + :ivar quota: QuotaOperations operations + :vartype quota: azure.mgmt.reservations.aio.operations.QuotaOperations :ivar reservation: ReservationOperations operations :vartype reservation: azure.mgmt.reservations.aio.operations.ReservationOperations :ivar reservation_order: ReservationOrderOperations operations :vartype reservation_order: azure.mgmt.reservations.aio.operations.ReservationOrderOperations - :ivar operation: OperationOperations operations - :vartype operation: azure.mgmt.reservations.aio.operations.OperationOperations :ivar calculate_refund: CalculateRefundOperations operations :vartype calculate_refund: azure.mgmt.reservations.aio.operations.CalculateRefundOperations :ivar return_operations: ReturnOperations operations @@ -52,34 +66,73 @@ class AzureReservationAPI( :vartype calculate_exchange: azure.mgmt.reservations.aio.operations.CalculateExchangeOperations :ivar exchange: ExchangeOperations operations :vartype exchange: azure.mgmt.reservations.aio.operations.ExchangeOperations - :ivar quota: QuotaOperations operations - :vartype quota: azure.mgmt.reservations.aio.operations.QuotaOperations - :ivar quota_request_status: QuotaRequestStatusOperations operations - :vartype quota_request_status: - azure.mgmt.reservations.aio.operations.QuotaRequestStatusOperations - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :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 cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( - self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + self, + credential: "AsyncTokenCredential", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any ) -> None: - self._config = AzureReservationAPIConfiguration(credential=credential, **kwargs) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _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 = ReservationsMgmtClientConfiguration( + credential=credential, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _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 + ) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False + self.quota_request_status = QuotaRequestStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) + self.quota = QuotaOperations(self._client, self._config, self._serialize, self._deserialize) self.reservation = ReservationOperations(self._client, self._config, self._serialize, self._deserialize) self.reservation_order = ReservationOrderOperations( self._client, self._config, self._serialize, self._deserialize ) - self.operation = OperationOperations(self._client, self._config, self._serialize, self._deserialize) self.calculate_refund = CalculateRefundOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -88,18 +141,16 @@ def __init__( self._client, self._config, self._serialize, self._deserialize ) self.exchange = ExchangeOperations(self._client, self._config, self._serialize, self._deserialize) - self.quota = QuotaOperations(self._client, self._config, self._serialize, self._deserialize) - self.quota_request_status = QuotaRequestStatusOperations( - self._client, self._config, self._serialize, self._deserialize - ) - 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 @@ -112,13 +163,17 @@ 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) -> "AzureReservationAPI": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py index a22504dccc2d..4988b03e05b1 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_configuration.py @@ -2,41 +2,53 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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 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 TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials_async import AsyncTokenCredential -class AzureReservationAPIConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AzureReservationAPI. +class ReservationsMgmtClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for ReservationsMgmtClient. 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 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 """ - def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(AzureReservationAPIConfiguration, self).__init__(**kwargs) + def __init__( + self, + credential: "AsyncTokenCredential", + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential + self.base_url = base_url + self.cloud_setting = cloud_setting self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-reservations/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -45,9 +57,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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_patch.py index f99e77fef986..ea765788358a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_patch.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/_patch.py @@ -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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py index d6b78b37947f..95366886f02a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/__init__.py @@ -2,36 +2,41 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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 ._reservation_operations import ReservationOperations -from ._azure_reservation_api_operations import AzureReservationAPIOperationsMixin -from ._reservation_order_operations import ReservationOrderOperations -from ._operation_operations import OperationOperations -from ._calculate_refund_operations import CalculateRefundOperations -from ._return_operations_operations import ReturnOperations -from ._calculate_exchange_operations import CalculateExchangeOperations -from ._exchange_operations import ExchangeOperations -from ._quota_operations import QuotaOperations -from ._quota_request_status_operations import QuotaRequestStatusOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import QuotaRequestStatusOperations # type: ignore +from ._operations import OperationOperations # type: ignore +from ._operations import QuotaOperations # type: ignore +from ._operations import ReservationOperations # type: ignore +from ._operations import ReservationOrderOperations # type: ignore +from ._operations import CalculateRefundOperations # type: ignore +from ._operations import ReturnOperations # type: ignore +from ._operations import CalculateExchangeOperations # type: ignore +from ._operations import ExchangeOperations # type: ignore +from ._operations import _ReservationsMgmtClientOperationsMixin # type: ignore # pylint: disable=unused-import 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__ = [ + "QuotaRequestStatusOperations", + "OperationOperations", + "QuotaOperations", "ReservationOperations", - "AzureReservationAPIOperationsMixin", "ReservationOrderOperations", - "OperationOperations", "CalculateRefundOperations", "ReturnOperations", "CalculateExchangeOperations", "ExchangeOperations", - "QuotaOperations", - "QuotaRequestStatusOperations", ] -__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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py deleted file mode 100644 index b695c4fd9e73..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_azure_reservation_api_operations.py +++ /dev/null @@ -1,219 +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 - -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._azure_reservation_api_operations import ( - build_get_applied_reservation_list_request, - build_get_catalog_request, -) -from .._vendor import AzureReservationAPIMixinABC - -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 AzureReservationAPIOperationsMixin(AzureReservationAPIMixinABC): - @distributed_trace - def get_catalog( - self, - subscription_id: str, - reserved_resource_type: Optional[str] = None, - location: Optional[str] = None, - publisher_id: Optional[str] = None, - offer_id: Optional[str] = None, - plan_id: Optional[str] = None, - filter: Optional[str] = None, - skip: Optional[float] = None, - take: Optional[float] = None, - **kwargs: Any - ) -> AsyncIterable["_models.Catalog"]: - """Get the regions and skus that are available for RI purchase for the specified Azure - subscription. - - Get the regions and skus that are available for RI purchase for the specified Azure - subscription. - - :param subscription_id: Id of the subscription. Required. - :type subscription_id: str - :param reserved_resource_type: The type of the resource for which the skus should be provided. - Default value is None. - :type reserved_resource_type: str - :param location: Filters the skus based on the location specified in this parameter. This can - be an Azure region or global. Default value is None. - :type location: str - :param publisher_id: Publisher id used to get the third party products. Default value is None. - :type publisher_id: str - :param offer_id: Offer id used to get the third party products. Default value is None. - :type offer_id: str - :param plan_id: Plan id used to get the third party products. Default value is None. - :type plan_id: str - :param filter: May be used to filter by Catalog properties. The filter supports 'eq', 'or', and - 'and'. Default value is None. - :type filter: str - :param skip: The number of reservations to skip from the list before returning results. Default - value is None. - :type skip: float - :param take: To number of reservations to return. Default value is None. - :type take: float - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Catalog or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.Catalog] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.CatalogsResult] = 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_get_catalog_request( - subscription_id=subscription_id, - reserved_resource_type=reserved_resource_type, - location=location, - publisher_id=publisher_id, - offer_id=offer_id, - plan_id=plan_id, - filter=filter, - skip=skip, - take=take, - api_version=api_version, - template_url=self.get_catalog.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - 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("CatalogsResult", 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( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - get_catalog.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs"} - - @distributed_trace_async - async def get_applied_reservation_list(self, subscription_id: str, **kwargs: Any) -> _models.AppliedReservations: - """Get list of applicable ``Reservation``\ s. - - Get applicable ``Reservation``\ s that are applied to this subscription or a resource group - under this subscription. - - :param subscription_id: Id of the subscription. Required. - :type subscription_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AppliedReservations or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.AppliedReservations - :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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.AppliedReservations] = kwargs.pop("cls", None) - - request = build_get_applied_reservation_list_request( - subscription_id=subscription_id, - api_version=api_version, - template_url=self.get_applied_reservation_list.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("AppliedReservations", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get_applied_reservation_list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py deleted file mode 100644 index 1d7ad4fab052..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_exchange_operations.py +++ /dev/null @@ -1,258 +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, Optional, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._calculate_exchange_operations import build_post_request -from .._vendor import AzureReservationAPIMixinABC - -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 CalculateExchangeOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`calculate_exchange` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - async def _post_initial( - self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any - ) -> Optional[_models.CalculateExchangeOperationResultResponse]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.CalculateExchangeOperationResultResponse]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CalculateExchangeRequest") - - request = build_post_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._post_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("CalculateExchangeOperationResultResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} - - @overload - async def begin_post( - self, body: _models.CalculateExchangeRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: - """Calculates the refund amounts and price of the new purchases. - - Calculates price for exchanging ``Reservations`` if there are no policy errors. - - :param body: Request containing purchases and refunds that need to be executed. Required. - :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either - CalculateExchangeOperationResultResponse or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_post( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: - """Calculates the refund amounts and price of the new purchases. - - Calculates price for exchanging ``Reservations`` if there are no policy errors. - - :param body: Request containing purchases and refunds that need to be executed. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either - CalculateExchangeOperationResultResponse or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_post( - self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any - ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: - """Calculates the refund amounts and price of the new purchases. - - Calculates price for exchanging ``Reservations`` if there are no policy errors. - - :param body: Request containing purchases and refunds that need to be executed. Is either a - CalculateExchangeRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either - CalculateExchangeOperationResultResponse or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CalculateExchangeOperationResultResponse] = 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._post_initial( - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CalculateExchangeOperationResultResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py deleted file mode 100644 index 2e6a0c328016..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_calculate_refund_operations.py +++ /dev/null @@ -1,181 +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, Optional, TypeVar, Union, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._calculate_refund_operations import build_post_request -from .._vendor import AzureReservationAPIMixinABC - -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 CalculateRefundOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`calculate_refund` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def post( - self, - reservation_order_id: str, - body: _models.CalculateRefundRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CalculateRefundResponse: - """Calculate the refund amount of a reservation order. - - Calculate price for returning ``Reservations`` if there are no policy errors. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculating refund of a reservation. Required. - :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculateRefundResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def post( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CalculateRefundResponse: - """Calculate the refund amount of a reservation order. - - Calculate price for returning ``Reservations`` if there are no policy errors. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculating refund of a reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculateRefundResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def post( - self, reservation_order_id: str, body: Union[_models.CalculateRefundRequest, IO], **kwargs: Any - ) -> _models.CalculateRefundResponse: - """Calculate the refund amount of a reservation order. - - Calculate price for returning ``Reservations`` if there are no policy errors. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculating refund of a reservation. Is either a - CalculateRefundRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculateRefundResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CalculateRefundResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CalculateRefundRequest") - - request = build_post_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.post.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CalculateRefundResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/calculateRefund"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py deleted file mode 100644 index 0a8f6d0669c5..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_exchange_operations.py +++ /dev/null @@ -1,258 +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, Optional, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._exchange_operations import build_post_request -from .._vendor import AzureReservationAPIMixinABC - -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 ExchangeOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`exchange` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - async def _post_initial( - self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any - ) -> Optional[_models.ExchangeOperationResultResponse]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ExchangeOperationResultResponse]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ExchangeRequest") - - request = build_post_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._post_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ExchangeOperationResultResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} - - @overload - async def begin_post( - self, body: _models.ExchangeRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: - """Exchange Reservation(s). - - Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - - :param body: Request containing the refunds and purchases that need to be executed. Required. - :type body: ~azure.mgmt.reservations.models.ExchangeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ExchangeOperationResultResponse or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_post( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: - """Exchange Reservation(s). - - Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - - :param body: Request containing the refunds and purchases that need to be executed. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ExchangeOperationResultResponse or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_post( - self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any - ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: - """Exchange Reservation(s). - - Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - - :param body: Request containing the refunds and purchases that need to be executed. Is either a - ExchangeRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.ExchangeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ExchangeOperationResultResponse or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ExchangeOperationResultResponse] = 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._post_initial( - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ExchangeOperationResultResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py deleted file mode 100644 index 10336203e255..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operation_operations.py +++ /dev/null @@ -1,129 +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 - -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._operation_operations import build_list_request -from .._vendor import AzureReservationAPIMixinABC - -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 OperationOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`operation` 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, **kwargs: Any) -> AsyncIterable["_models.OperationResponse"]: - """Get operations. - - List all the operations. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationResponse or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.OperationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.OperationList] = 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( - 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: - request = HttpRequest("GET", next_link) - 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("OperationList", 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.Error, 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.Capacity/operations"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operations.py new file mode 100644 index 000000000000..f9cf58823477 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_operations.py @@ -0,0 +1,4321 @@ +# 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. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +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 ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ..._utils.utils import ClientMixinABC +from ..._validation import api_version_validation +from ...operations._operations import ( + build_calculate_exchange_post_request, + build_calculate_refund_post_request, + build_exchange_post_request, + build_operation_list_request, + build_quota_create_or_update_request, + build_quota_get_request, + build_quota_list_request, + build_quota_request_status_get_request, + build_quota_request_status_list_request, + build_quota_update_request, + build_reservation_archive_request, + build_reservation_available_scopes_request, + build_reservation_get_request, + build_reservation_list_all_request, + build_reservation_list_request, + build_reservation_list_revisions_request, + build_reservation_merge_request, + build_reservation_order_calculate_request, + build_reservation_order_change_directory_request, + build_reservation_order_get_request, + build_reservation_order_list_request, + build_reservation_order_purchase_request, + build_reservation_split_request, + build_reservation_unarchive_request, + build_reservation_update_request, + build_reservations_mgmt_get_applied_reservation_list_request, + build_reservations_mgmt_get_catalog_request, + build_return_operations_post_request, +) +from .._configuration import ReservationsMgmtClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +List = list + + +class QuotaRequestStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`quota_request_status` 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: ReservationsMgmtClientConfiguration = 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, subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any + ) -> _models.QuotaRequestDetails: + """For the specified Azure region (location), get the details and status of the quota request by + the quota request ID for the resources of the resource provider. The PUT request for the quota + (service limit) returns a response with the requestId parameter. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param id: Quota Request ID. Required. + :type id: str + :return: QuotaRequestDetails. The QuotaRequestDetails is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.QuotaRequestDetails + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[_models.QuotaRequestDetails] = kwargs.pop("cls", None) + + _request = build_quota_request_status_get_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + id=id, + api_version=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.ExceptionResponse, + 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.QuotaRequestDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + subscription_id: str, + provider_id: str, + location: str, + *, + filter: Optional[str] = None, + top: Optional[int] = None, + skiptoken: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.QuotaRequestDetails"]: + """For the specified Azure region (location), subscription, and resource provider, get the history + of the quota requests for the past year. To select specific quota requests, use the oData + filter. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :keyword filter: | Field | Supported operators | + |---------------------|------------------------| + |requestSubmitTime | ge, le, eq, gt, lt |. Default value is None. + :paramtype filter: str + :keyword top: Number of records to return. 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 includes + 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 QuotaRequestDetails + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[List[_models.QuotaRequestDetails]] = 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_quota_request_status_list_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + filter=filter, + top=top, + skiptoken=skiptoken, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.QuotaRequestDetails], + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class OperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`operation` 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: ReservationsMgmtClientConfiguration = 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) -> AsyncItemPaged["_models.OperationResponse"]: + """Get operations. + + List all the operations. + + :return: An iterator like instance of OperationResponse + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.OperationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.OperationResponse]] = 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_operation_list_request( + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.OperationResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class QuotaOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`quota` 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: ReservationsMgmtClientConfiguration = 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, subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any + ) -> _models.CurrentQuotaLimitBase: + """Get the current quota (service limit) and usage of a resource. You can use the response from + the GET operation to submit quota update request. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :return: CurrentQuotaLimitBase. The CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[_models.CurrentQuotaLimitBase] = kwargs.pop("cls", None) + + _request = build_quota_get_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + api_version=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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CurrentQuotaLimitBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + async def _create_or_update_initial( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(create_quota_request, (IOBase, bytes)): + _content = create_quota_request + else: + _content = json.dumps(create_quota_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_quota_create_or_update_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + api_version=api_version, + content_type=content_type, + 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 = 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, 201]: + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Is one of the following types: + CurrentQuotaLimitBase, JSON, IO[bytes] Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or JSON or + IO[bytes] + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CurrentQuotaLimitBase] = 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._create_or_update_initial( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + create_quota_request=create_quota_request, + api_version=api_version, + content_type=content_type, + 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.CurrentQuotaLimitBase, 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.CurrentQuotaLimitBase].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CurrentQuotaLimitBase]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(create_quota_request, (IOBase, bytes)): + _content = create_quota_request + else: + _content = json.dumps(create_quota_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_quota_update_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + api_version=api_version, + content_type=content_type, + 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 = 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, 201]: + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Is one of the following types: + CurrentQuotaLimitBase, JSON, IO[bytes] Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or JSON or + IO[bytes] + :return: An instance of AsyncLROPoller that returns CurrentQuotaLimitBase. The + CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CurrentQuotaLimitBase] = 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._update_initial( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + create_quota_request=create_quota_request, + api_version=api_version, + content_type=content_type, + 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.CurrentQuotaLimitBase, 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.CurrentQuotaLimitBase].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CurrentQuotaLimitBase]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list( + self, subscription_id: str, provider_id: str, location: str, **kwargs: Any + ) -> AsyncItemPaged["_models.CurrentQuotaLimitBase"]: + """Gets a list of current quotas (service limits) and usage for all resources. The response from + the list quota operation can be leveraged to request quota updates. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :return: An iterator like instance of CurrentQuotaLimitBase + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[List[_models.CurrentQuotaLimitBase]] = 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_quota_list_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.CurrentQuotaLimitBase], + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class ReservationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`reservation` 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: ReservationsMgmtClientConfiguration = 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, reservation_order_id: str, reservation_id: str, *, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationResponse: + """Get ``Reservation`` details. + + Get specific ``Reservation`` details. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :keyword expand: Supported value of this query is renewProperties. Default value is None. + :paramtype expand: str + :return: ReservationResponse. The ReservationResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ReservationResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[_models.ReservationResponse] = kwargs.pop("cls", None) + + _request = build_reservation_get_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + expand=expand, + api_version=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.Error, + 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.ReservationResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_initial( + self, + reservation_order_id: str, + reservation_id: str, + parameters: Union[_models.Patch, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = 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_reservation_update_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: _models.Patch, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Required. + :type parameters: ~azure.mgmt.reservations.models.Patch + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationResponse. The + ReservationResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationResponse. The + ReservationResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationResponse. The + ReservationResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: Union[_models.Patch, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Is one of the following + types: Patch, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.reservations.models.Patch or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns ReservationResponse. The + ReservationResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReservationResponse] = 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._update_initial( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + 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.ReservationResponse, 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.ReservationResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ReservationResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list(self, reservation_order_id: str, **kwargs: Any) -> AsyncItemPaged["_models.ReservationResponse"]: + """Get ``Reservation``s in a given reservation Order. + + List ``Reservation``s within a single ``ReservationOrder``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :return: An iterator like instance of ReservationResponse + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationResponse]] = 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_list_request( + reservation_order_id=reservation_order_id, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + async def _available_scopes_initial( + self, + reservation_order_id: str, + reservation_id: str, + body: Union[_models.AvailableScopeRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_available_scopes_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + content_type=content_type, + 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 = 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]: + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: _models.AvailableScopeRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Required. + :type body: 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: An instance of AsyncLROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: Union[_models.AvailableScopeRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Is one of the following types: + AvailableScopeRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AvailableScopeProperties] = 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._available_scopes_initial( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + 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_headers = {} + response = pipeline_response.http_response + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = _deserialize(_models.AvailableScopeProperties, response.json()) + if cls: + return cls(pipeline_response, deserialized, response_headers) # 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.AvailableScopeProperties].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.AvailableScopeProperties]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + async def archive(self, reservation_order_id: str, reservation_id: str, **kwargs: Any) -> None: + """Archive a ``Reservation``. + + Archiving a ``Reservation`` moves it to ``Archived`` state. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_reservation_archive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace_async + async def unarchive(self, reservation_order_id: str, reservation_id: str, **kwargs: Any) -> None: + """Unarchive a ``Reservation``. + + Restores a ``Reservation`` to the state it was before archiving. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_reservation_unarchive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_revisions( + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> AsyncItemPaged["_models.ReservationResponse"]: + """Get ``Reservation`` revisions. + + List of all the revisions for the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :return: An iterator like instance of ReservationResponse + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationResponse]] = 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_list_revisions_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + async def _split_initial( + self, reservation_order_id: str, body: Union[_models.SplitRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_split_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_split( + self, + reservation_order_id: str, + body: _models.SplitRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: ~azure.mgmt.reservations.models.SplitRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_split( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_split( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_split( + self, reservation_order_id: str, body: Union[_models.SplitRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Is one of the following types: + SplitRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.SplitRequest or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.ReservationResponse]] = 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._split_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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(List[_models.ReservationResponse], 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[List[_models.ReservationResponse]].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[List[_models.ReservationResponse]]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _merge_initial( + self, reservation_order_id: str, body: Union[_models.MergeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_merge_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_merge( + self, + reservation_order_id: str, + body: _models.MergeRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: ~azure.mgmt.reservations.models.MergeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_merge( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_merge( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_merge( + self, reservation_order_id: str, body: Union[_models.MergeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Is one of the + following types: MergeRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.MergeRequest or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.ReservationResponse]] = 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._merge_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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(List[_models.ReservationResponse], 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[List[_models.ReservationResponse]].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[List[_models.ReservationResponse]]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_all( + self, + *, + filter: Optional[str] = None, + orderby: Optional[str] = None, + refresh_summary: Optional[str] = None, + skiptoken: Optional[float] = None, + selected_state: Optional[str] = None, + take: Optional[float] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.ReservationResponse"]: + """List the reservations and the roll up counts of reservations group by provisioning states that + the user has access to in the current tenant. + + :keyword filter: May be used to filter by reservation properties. The filter supports 'eq', + 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation + properties include sku/name, properties/{appliedScopeType, archived, displayName, + displayProvisioningState, effectiveDateTime, expiryDate, expiryDateTime, provisioningState, + quantity, renew, reservedResourceType, term, userFriendlyAppliedScopeType, + userFriendlyRenewState}. Default value is None. + :paramtype filter: str + :keyword orderby: May be used to sort order by reservation properties. Default value is None. + :paramtype orderby: str + :keyword refresh_summary: To indicate whether to refresh the roll up counts of the reservations + group by provisioning states. Default value is None. + :paramtype refresh_summary: str + :keyword skiptoken: The number of reservations to skip from the list before returning results. + Default value is None. + :paramtype skiptoken: float + :keyword selected_state: The selected provisioning state. Default value is None. + :paramtype selected_state: str + :keyword take: To number of reservations to return. Default value is None. + :paramtype take: float + :return: An iterator like instance of ReservationResponse + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationResponse]] = 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_list_all_request( + filter=filter, + orderby=orderby, + refresh_summary=refresh_summary, + skiptoken=skiptoken, + selected_state=selected_state, + take=take, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationResponse], + 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 ReservationOrderOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`reservation_order` 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: ReservationsMgmtClientConfiguration = 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, reservation_order_id: str, *, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationOrderResponse: + """Get a specific ``ReservationOrder``. + + Get the details of the ``ReservationOrder``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :keyword expand: May be used to expand the planInformation. Default value is None. + :paramtype expand: str + :return: ReservationOrderResponse. The ReservationOrderResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.reservations.models.ReservationOrderResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[_models.ReservationOrderResponse] = kwargs.pop("cls", None) + + _request = build_reservation_order_get_request( + reservation_order_id=reservation_order_id, + expand=expand, + api_version=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.Error, + 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.ReservationOrderResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _purchase_initial( + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_order_purchase_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_purchase( + self, + reservation_order_id: str, + body: _models.PurchaseRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_purchase( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_purchase( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_purchase( + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Is one of the following + types: PurchaseRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReservationOrderResponse] = 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._purchase_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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.ReservationOrderResponse, 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.ReservationOrderResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ReservationOrderResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.ReservationOrderResponse"]: + """Get all ``ReservationOrder``s. + + List of all the ``ReservationOrder``s that the user has access to in the current tenant. + + :return: An iterator like instance of ReservationOrderResponse + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationOrderResponse]] = 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_order_list_request( + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationOrderResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def change_directory( + self, + reservation_order_id: str, + body: _models.ChangeDirectoryRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def change_directory( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def change_directory( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def change_directory( + self, reservation_order_id: str, body: Union[_models.ChangeDirectoryRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Is one of the + following types: ChangeDirectoryRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest or JSON or IO[bytes] + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ChangeDirectoryResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_order_change_directory_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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]: + 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.Error, + 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.ChangeDirectoryResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def calculate( + self, body: _models.PurchaseRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def calculate( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def calculate( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Required. + :type body: 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: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def calculate( + self, body: Union[_models.PurchaseRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Is one of the following types: PurchaseRequest, JSON, IO[bytes] + Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or JSON or IO[bytes] + :return: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CalculatePriceResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_order_calculate_request( + api_version=api_version, + content_type=content_type, + 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]: + 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.Error, + 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.CalculatePriceResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CalculateRefundOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`calculate_refund` 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: ReservationsMgmtClientConfiguration = 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") + + @overload + async def post( + self, + reservation_order_id: str, + body: _models.CalculateRefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def post( + self, reservation_order_id: str, body: Union[_models.CalculateRefundRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Is one of the + following types: CalculateRefundRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest or JSON or IO[bytes] + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CalculateRefundResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_calculate_refund_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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]: + 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.Error, + 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.CalculateRefundResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ReturnOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`return_operations` 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: ReservationsMgmtClientConfiguration = 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") + + async def _post_initial( + self, reservation_order_id: str, body: Union[_models.RefundRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_return_operations_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_post( + self, + reservation_order_id: str, + body: _models.RefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_post( + self, reservation_order_id: str, body: Union[_models.RefundRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Is one of the following types: + RefundRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReservationOrderResponse] = 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._post_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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.ReservationOrderResponse, 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.ReservationOrderResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ReservationOrderResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class CalculateExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`calculate_exchange` 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: ReservationsMgmtClientConfiguration = 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") + + async def _post_initial( + self, body: Union[_models.CalculateExchangeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_calculate_exchange_post_request( + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_post( + self, body: _models.CalculateExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CalculateExchangeOperationResultResponse. + The CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns CalculateExchangeOperationResultResponse. + The CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Required. + :type body: 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: An instance of AsyncLROPoller that returns CalculateExchangeOperationResultResponse. + The CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_post( + self, body: Union[_models.CalculateExchangeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Is one of the following types: CalculateExchangeRequest, JSON, + IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns CalculateExchangeOperationResultResponse. + The CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CalculateExchangeOperationResultResponse] = 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._post_initial( + body=body, + api_version=api_version, + content_type=content_type, + 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.CalculateExchangeOperationResultResponse, 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.CalculateExchangeOperationResultResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.CalculateExchangeOperationResultResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class ExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.aio.ReservationsMgmtClient`'s + :attr:`exchange` 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: ReservationsMgmtClientConfiguration = 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") + + async def _post_initial( + self, body: Union[_models.ExchangeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_exchange_post_request( + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + async def begin_post( + self, body: _models.ExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Required. + :type body: 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: An instance of AsyncLROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_post( + self, body: Union[_models.ExchangeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> AsyncLROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Is one of the following types: ExchangeRequest, JSON, IO[bytes] + Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ExchangeOperationResultResponse] = 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._post_initial( + body=body, + api_version=api_version, + content_type=content_type, + 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.ExchangeOperationResultResponse, 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.ExchangeOperationResultResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.ExchangeOperationResultResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class _ReservationsMgmtClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], ReservationsMgmtClientConfiguration] +): + + @distributed_trace + @api_version_validation( + method_added_on="2022-11-01", + params_added_on={ + "2022-11-01": [ + "api_version", + "subscription_id", + "reserved_resource_type", + "location", + "publisher_id", + "offer_id", + "plan_id", + "filter", + "skip", + "take", + "accept", + ] + }, + api_versions_list=["2022-11-01"], + ) + def get_catalog( + self, + subscription_id: str, + *, + reserved_resource_type: Optional[str] = None, + location: Optional[str] = None, + publisher_id: Optional[str] = None, + offer_id: Optional[str] = None, + plan_id: Optional[str] = None, + filter: Optional[str] = None, + skip: Optional[float] = None, + take: Optional[float] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.Catalog"]: + """Get the regions and skus that are available for RI purchase for the specified Azure + subscription. + + Get the regions and skus that are available for RI purchase for the specified Azure + subscription. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :keyword reserved_resource_type: The type of the resource for which the skus should be + provided. Default value is None. + :paramtype reserved_resource_type: str + :keyword location: Filters the skus based on the location specified in this parameter. This can + be an azure region or global. Default value is None. + :paramtype location: str + :keyword publisher_id: Publisher id used to get the third party products. Default value is + None. + :paramtype publisher_id: str + :keyword offer_id: Offer id used to get the third party products. Default value is None. + :paramtype offer_id: str + :keyword plan_id: Plan id used to get the third party products. Default value is None. + :paramtype plan_id: str + :keyword filter: May be used to filter by Catalog properties. The filter supports 'eq', 'or', + and 'and'. Default value is None. + :paramtype filter: str + :keyword skip: The number of reservations to skip from the list before returning results. + Default value is None. + :paramtype skip: float + :keyword take: To number of reservations to return. Default value is None. + :paramtype take: float + :return: An iterator like instance of Catalog + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.Catalog] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.Catalog]] = 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_mgmt_get_catalog_request( + subscription_id=subscription_id, + reserved_resource_type=reserved_resource_type, + location=location, + publisher_id=publisher_id, + offer_id=offer_id, + plan_id=plan_id, + filter=filter, + skip=skip, + take=take, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.Catalog], + 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( # type: ignore # 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + @api_version_validation( + method_added_on="2022-11-01", + params_added_on={"2022-11-01": ["api_version", "subscription_id", "accept"]}, + api_versions_list=["2022-11-01"], + ) + async def get_applied_reservation_list(self, subscription_id: str, **kwargs: Any) -> _models.AppliedReservations: + """Get list of applicable ``Reservation``s. + + Get applicable ``Reservation``s that are applied to this subscription or a resource group under + this subscription. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :return: AppliedReservations. The AppliedReservations is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.AppliedReservations + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[_models.AppliedReservations] = kwargs.pop("cls", None) + + _request = build_reservations_mgmt_get_applied_reservation_list_request( + subscription_id=subscription_id, + api_version=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( # type: ignore # 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.Error, + 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.AppliedReservations, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_patch.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_patch.py @@ -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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py deleted file mode 100644 index f6f4bdcd9cde..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_operations.py +++ /dev/null @@ -1,793 +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, cast, overload - -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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._quota_operations import ( - build_create_or_update_request, - build_get_request, - build_list_request, - build_update_request, -) -from .._vendor import AzureReservationAPIMixinABC - -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 QuotaOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`quota` 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, subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any - ) -> _models.CurrentQuotaLimitBase: - """Get the current quota (service limit) and usage of a resource. You can use the response from - the GET operation to submit quota update request. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CurrentQuotaLimitBase or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.CurrentQuotaLimitBase] = kwargs.pop("cls", None) - - request = build_get_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - api_version=api_version, - template_url=self.get.metadata["url"], - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - async def _create_or_update_initial( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: - 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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] = kwargs.pop( - "cls", None - ) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_quota_request, (IO, bytes)): - _content = create_quota_request - else: - _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") - - request = build_create_or_update_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._create_or_update_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - @overload - async def begin_create_or_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: _models.CurrentQuotaLimitBase, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: - """Create or update the quota (service limits) of a resource to the requested value. - Steps: - - - #. Make the Get request to get the quota information for specific resource. - #. To increase the quota, update the limit field in the response from Get request to new value. - #. Submit the JSON to the quota request API to update the quota. - The Create quota request may be constructed as follows. The PUT operation can be used to - update the quota. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Quota requests payload. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance - of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_or_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: - """Create or update the quota (service limits) of a resource to the requested value. - Steps: - - - #. Make the Get request to get the quota information for specific resource. - #. To increase the quota, update the limit field in the response from Get request to new value. - #. Submit the JSON to the quota request API to update the quota. - The Create quota request may be constructed as follows. The PUT operation can be used to - update the quota. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Quota requests payload. Required. - :type create_quota_request: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance - of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_or_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: - """Create or update the quota (service limits) of a resource to the requested value. - Steps: - - - #. Make the Get request to get the quota information for specific resource. - #. To increase the quota, update the limit field in the response from Get request to new value. - #. Submit the JSON to the quota request API to update the quota. - The Create quota request may be constructed as follows. The PUT operation can be used to - update the quota. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Quota requests payload. Is either a CurrentQuotaLimitBase type or - a IO type. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance - of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CurrentQuotaLimitBase] = 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._create_or_update_initial( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - create_quota_request=create_quota_request, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - async def _update_initial( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: - 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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] = kwargs.pop( - "cls", None - ) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_quota_request, (IO, bytes)): - _content = create_quota_request - else: - _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") - - request = build_update_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._update_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - _update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - @overload - async def begin_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: _models.CurrentQuotaLimitBase, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: - """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. - • To increase the quota, update the limit field from the GET response to a new value. - • To update the quota value, submit the JSON response to the quota request API to update the - quota. - • To update the quota. use the PATCH operation. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Payload for the quota request. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance - of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: - """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. - • To increase the quota, update the limit field from the GET response to a new value. - • To update the quota value, submit the JSON response to the quota request API to update the - quota. - • To update the quota. use the PATCH operation. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Payload for the quota request. Required. - :type create_quota_request: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance - of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> AsyncLROPoller[_models.CurrentQuotaLimitBase]: - """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. - • To increase the quota, update the limit field from the GET response to a new value. - • To update the quota value, submit the JSON response to the quota request API to update the - quota. - • To update the quota. use the PATCH operation. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Payload for the quota request. Is either a CurrentQuotaLimitBase - type or a IO type. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either CurrentQuotaLimitBase or An instance - of AsyncLROPoller that returns either QuotaRequestSubmitResponse201 or the result of - cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CurrentQuotaLimitBase] = 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._update_initial( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - create_quota_request=create_quota_request, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - @distributed_trace - def list( - self, subscription_id: str, provider_id: str, location: str, **kwargs: Any - ) -> AsyncIterable["_models.CurrentQuotaLimitBase"]: - """Gets a list of current quotas (service limits) and usage for all resources. The response from - the list quota operation can be leveraged to request quota updates. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CurrentQuotaLimitBase or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.QuotaLimits] = 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( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - 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: - request = HttpRequest("GET", next_link) - 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("QuotaLimits", 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py deleted file mode 100644 index 481d7a3c94fc..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_quota_request_status_operations.py +++ /dev/null @@ -1,238 +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 - -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._quota_request_status_operations import build_get_request, build_list_request -from .._vendor import AzureReservationAPIMixinABC - -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 QuotaRequestStatusOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`quota_request_status` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get( - self, subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any - ) -> _models.QuotaRequestDetails: - """For the specified Azure region (location), get the details and status of the quota request by - the quota request ID for the resources of the resource provider. The PUT request for the quota - (service limit) returns a response with the requestId parameter. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param id: Quota Request ID. Required. - :type id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: QuotaRequestDetails or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.QuotaRequestDetails - :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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.QuotaRequestDetails] = kwargs.pop("cls", None) - - request = build_get_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - id=id, - api_version=api_version, - template_url=self.get.metadata["url"], - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("QuotaRequestDetails", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}" - } - - @distributed_trace - def list( - self, - subscription_id: str, - provider_id: str, - location: str, - filter: Optional[str] = None, - top: Optional[int] = None, - skiptoken: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterable["_models.QuotaRequestDetails"]: - """For the specified Azure region (location), subscription, and resource provider, get the history - of the quota requests for the past year. To select specific quota requests, use the oData - filter. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param filter: .. list-table:: - :header-rows: 1 - - * - Field - - Supported operators - * - requestSubmitTime - - ge, le, eq, gt, lt. Default value is None. - :type filter: str - :param top: Number of records to return. Default value is None. - :type top: int - :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 includes 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 QuotaRequestDetails or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetails] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.QuotaRequestDetailsList] = 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( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - 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: - request = HttpRequest("GET", next_link) - 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("QuotaRequestDetailsList", 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py deleted file mode 100644 index ef791f0faa4b..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_operations.py +++ /dev/null @@ -1,1391 +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, List, Optional, TypeVar, Union, cast, overload - -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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._reservation_operations import ( - build_archive_request, - build_available_scopes_request, - build_get_request, - build_list_all_request, - build_list_request, - build_list_revisions_request, - build_merge_request, - build_split_request, - build_unarchive_request, - build_update_request, -) -from .._vendor import AzureReservationAPIMixinABC - -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 ReservationOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`reservation` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - async def _available_scopes_initial( - self, - reservation_order_id: str, - reservation_id: str, - body: Union[_models.AvailableScopeRequest, IO], - **kwargs: Any - ) -> _models.AvailableScopeProperties: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AvailableScopeProperties] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "AvailableScopeRequest") - - request = build_available_scopes_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._available_scopes_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("AvailableScopeProperties", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - _available_scopes_initial.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes" - } - - @overload - async def begin_available_scopes( - self, - reservation_order_id: str, - reservation_id: str, - body: _models.AvailableScopeRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.AvailableScopeProperties]: - """Get Available Scopes for ``Reservation``. - - Check whether the scopes from request is valid for ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param body: Scopes to be checked for eligibility. Required. - :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either AvailableScopeProperties or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_available_scopes( - self, - reservation_order_id: str, - reservation_id: str, - body: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.AvailableScopeProperties]: - """Get Available Scopes for ``Reservation``. - - Check whether the scopes from request is valid for ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param body: Scopes to be checked for eligibility. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either AvailableScopeProperties or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_available_scopes( - self, - reservation_order_id: str, - reservation_id: str, - body: Union[_models.AvailableScopeRequest, IO], - **kwargs: Any - ) -> AsyncLROPoller[_models.AvailableScopeProperties]: - """Get Available Scopes for ``Reservation``. - - Check whether the scopes from request is valid for ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param body: Scopes to be checked for eligibility. Is either a AvailableScopeRequest type or a - IO type. Required. - :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either AvailableScopeProperties or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AvailableScopeProperties] = 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._available_scopes_initial( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("AvailableScopeProperties", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_available_scopes.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes" - } - - async def _split_initial( - self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any - ) -> Optional[List[_models.ReservationResponse]]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[List[_models.ReservationResponse]]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "SplitRequest") - - request = build_split_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._split_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _split_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} - - @overload - async def begin_split( - self, - reservation_order_id: str, - body: _models.SplitRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[List[_models.ReservationResponse]]: - """Split the ``Reservation``. - - Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to Split a reservation item. Required. - :type body: ~azure.mgmt.reservations.models.SplitRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_split( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[List[_models.ReservationResponse]]: - """Split the ``Reservation``. - - Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to Split a reservation item. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_split( - self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any - ) -> AsyncLROPoller[List[_models.ReservationResponse]]: - """Split the ``Reservation``. - - Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to Split a reservation item. Is either a SplitRequest type or a - IO type. Required. - :type body: ~azure.mgmt.reservations.models.SplitRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[List[_models.ReservationResponse]] = 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._split_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_split.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} - - async def _merge_initial( - self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any - ) -> Optional[List[_models.ReservationResponse]]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[List[_models.ReservationResponse]]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "MergeRequest") - - request = build_merge_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._merge_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _merge_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} - - @overload - async def begin_merge( - self, - reservation_order_id: str, - body: _models.MergeRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[List[_models.ReservationResponse]]: - """Merges two ``Reservation``\ s. - - Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s - being merged must have same properties. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. Required. - :type body: ~azure.mgmt.reservations.models.MergeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_merge( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[List[_models.ReservationResponse]]: - """Merges two ``Reservation``\ s. - - Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s - being merged must have same properties. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_merge( - self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any - ) -> AsyncLROPoller[List[_models.ReservationResponse]]: - """Merges two ``Reservation``\ s. - - Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s - being merged must have same properties. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. Is either a - MergeRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.MergeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either list of ReservationResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[List[_models.ReservationResponse]] = 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._merge_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_merge.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} - - @distributed_trace - def list(self, reservation_order_id: str, **kwargs: Any) -> AsyncIterable["_models.ReservationResponse"]: - """Get ``Reservation``\ s in a given reservation Order. - - List ``Reservation``\ s within a single ``ReservationOrder``. - - :param reservation_order_id: Order Id of the reservation. Required. - :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 ReservationResponse or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationList] = 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( - 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: - request = HttpRequest("GET", next_link) - 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("ReservationList", 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.Error, 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.Capacity/reservationOrders/{reservationOrderId}/reservations"} - - @distributed_trace_async - async def get( - self, reservation_order_id: str, reservation_id: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.ReservationResponse: - """Get ``Reservation`` details. - - Get specific ``Reservation`` details. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param expand: Supported value of this query is renewProperties. Default value is None. - :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ReservationResponse - :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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationResponse] = kwargs.pop("cls", None) - - request = build_get_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - expand=expand, - api_version=api_version, - template_url=self.get.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ReservationResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" - } - - async def _update_initial( - self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any - ) -> Optional[_models.ReservationResponse]: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ReservationResponse]] = 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, "Patch") - - request = build_update_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._update_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ReservationResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _update_initial.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" - } - - @overload - async def begin_update( - self, - reservation_order_id: str, - reservation_id: str, - parameters: _models.Patch, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationResponse]: - """Updates a ``Reservation``. - - Updates the applied scopes of the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param parameters: Information needed to patch a reservation item. Required. - :type parameters: ~azure.mgmt.reservations.models.Patch - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationResponse or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update( - self, - reservation_order_id: str, - reservation_id: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationResponse]: - """Updates a ``Reservation``. - - Updates the applied scopes of the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param parameters: Information needed to patch a reservation item. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationResponse or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update( - self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationResponse]: - """Updates a ``Reservation``. - - Updates the applied scopes of the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param parameters: Information needed to patch a reservation item. Is either a Patch type or a - IO type. Required. - :type parameters: ~azure.mgmt.reservations.models.Patch or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationResponse or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationResponse] = 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._update_initial( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ReservationResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" - } - - @distributed_trace_async - async def archive( # pylint: disable=inconsistent-return-statements - self, reservation_order_id: str, reservation_id: str, **kwargs: Any - ) -> None: - """Archive a ``Reservation``. - - Archiving a ``Reservation`` moves it to ``Archived`` state. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_archive_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - template_url=self.archive.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - archive.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/archive" - } - - @distributed_trace_async - async def unarchive( # pylint: disable=inconsistent-return-statements - self, reservation_order_id: str, reservation_id: str, **kwargs: Any - ) -> None: - """Unarchive a ``Reservation``. - - Restores a ``Reservation`` to the state it was before archiving. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_unarchive_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - template_url=self.unarchive.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - unarchive.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/unarchive" - } - - @distributed_trace - def list_revisions( - self, reservation_order_id: str, reservation_id: str, **kwargs: Any - ) -> AsyncIterable["_models.ReservationResponse"]: - """Get ``Reservation`` revisions. - - List of all the revisions for the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationResponse or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationList] = 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_revisions_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - template_url=self.list_revisions.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - 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("ReservationList", 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_revisions.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions" - } - - @distributed_trace - def list_all( - self, - filter: Optional[str] = None, - orderby: Optional[str] = None, - refresh_summary: Optional[str] = None, - skiptoken: Optional[float] = None, - selected_state: Optional[str] = None, - take: Optional[float] = None, - **kwargs: Any - ) -> AsyncIterable["_models.ReservationResponse"]: - """List the reservations and the roll up counts of reservations group by provisioning states that - the user has access to in the current tenant. - - :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', - and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation - properties include sku/name, properties/{appliedScopeType, archived, displayName, - displayProvisioningState, effectiveDateTime, expiryDate, expiryDateTime, provisioningState, - quantity, renew, reservedResourceType, term, userFriendlyAppliedScopeType, - userFriendlyRenewState}. Default value is None. - :type filter: str - :param orderby: May be used to sort order by reservation properties. Default value is None. - :type orderby: str - :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations - group by provisioning states. Default value is None. - :type refresh_summary: str - :param skiptoken: The number of reservations to skip from the list before returning results. - Default value is None. - :type skiptoken: float - :param selected_state: The selected provisioning state. Default value is None. - :type selected_state: str - :param take: To number of reservations to return. Default value is None. - :type take: float - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationResponse or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationsListResult] = 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_all_request( - filter=filter, - orderby=orderby, - refresh_summary=refresh_summary, - skiptoken=skiptoken, - selected_state=selected_state, - take=take, - api_version=api_version, - template_url=self.list_all.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - 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("ReservationsListResult", 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_all.metadata = {"url": "/providers/Microsoft.Capacity/reservations"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py deleted file mode 100644 index debdaf5eb08f..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_reservation_order_operations.py +++ /dev/null @@ -1,651 +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, cast, overload - -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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._reservation_order_operations import ( - build_calculate_request, - build_change_directory_request, - build_get_request, - build_list_request, - build_purchase_request, -) -from .._vendor import AzureReservationAPIMixinABC - -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 ReservationOrderOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`reservation_order` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def calculate( - self, body: _models.PurchaseRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CalculatePriceResponse: - """Calculate price for a ``ReservationOrder``. - - Calculate price for placing a ``ReservationOrder``. - - :param body: Information needed for calculate or purchase reservation. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculatePriceResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def calculate( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CalculatePriceResponse: - """Calculate price for a ``ReservationOrder``. - - Calculate price for placing a ``ReservationOrder``. - - :param body: Information needed for calculate or purchase reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculatePriceResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def calculate( - self, body: Union[_models.PurchaseRequest, IO], **kwargs: Any - ) -> _models.CalculatePriceResponse: - """Calculate price for a ``ReservationOrder``. - - Calculate price for placing a ``ReservationOrder``. - - :param body: Information needed for calculate or purchase reservation. Is either a - PurchaseRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculatePriceResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CalculatePriceResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "PurchaseRequest") - - request = build_calculate_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.calculate.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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CalculatePriceResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - calculate.metadata = {"url": "/providers/Microsoft.Capacity/calculatePrice"} - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.ReservationOrderResponse"]: - """Get all ``ReservationOrder``\ s. - - List of all the ``ReservationOrder``\ s that the user has access to in the current tenant. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationOrderResponse or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationOrderList] = 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( - 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: - request = HttpRequest("GET", next_link) - 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("ReservationOrderList", 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.Error, 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.Capacity/reservationOrders"} - - async def _purchase_initial( - self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any - ) -> _models.ReservationOrderResponse: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationOrderResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "PurchaseRequest") - - request = build_purchase_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._purchase_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - _purchase_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} - - @overload - async def begin_purchase( - self, - reservation_order_id: str, - body: _models.PurchaseRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationOrderResponse]: - """Purchase ``ReservationOrder``. - - Purchase ``ReservationOrder`` and create resource under the specified URI. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationOrderResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_purchase( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationOrderResponse]: - """Purchase ``ReservationOrder``. - - Purchase ``ReservationOrder`` and create resource under the specified URI. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationOrderResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_purchase( - self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationOrderResponse]: - """Purchase ``ReservationOrder``. - - Purchase ``ReservationOrder`` and create resource under the specified URI. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. Is either a - PurchaseRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationOrderResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationOrderResponse] = 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._purchase_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_purchase.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} - - @distributed_trace_async - async def get( - self, reservation_order_id: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.ReservationOrderResponse: - """Get a specific ``ReservationOrder``. - - Get the details of the ``ReservationOrder``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param expand: May be used to expand the planInformation. Default value is None. - :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationOrderResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ReservationOrderResponse - :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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationOrderResponse] = kwargs.pop("cls", None) - - request = build_get_request( - reservation_order_id=reservation_order_id, - expand=expand, - api_version=api_version, - template_url=self.get.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} - - @overload - async def change_directory( - self, - reservation_order_id: str, - body: _models.ChangeDirectoryRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ChangeDirectoryResponse: - """Change directory of ``ReservationOrder``. - - Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified - tenant id. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. Required. - :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChangeDirectoryResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def change_directory( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ChangeDirectoryResponse: - """Change directory of ``ReservationOrder``. - - Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified - tenant id. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChangeDirectoryResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def change_directory( - self, reservation_order_id: str, body: Union[_models.ChangeDirectoryRequest, IO], **kwargs: Any - ) -> _models.ChangeDirectoryResponse: - """Change directory of ``ReservationOrder``. - - Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified - tenant id. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. Is either a - ChangeDirectoryRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChangeDirectoryResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ChangeDirectoryResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ChangeDirectoryRequest") - - request = build_change_directory_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.change_directory.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChangeDirectoryResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - change_directory.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py deleted file mode 100644 index ba6c68655b89..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/aio/operations/_return_operations_operations.py +++ /dev/null @@ -1,270 +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, Optional, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from ... import models as _models -from ..._vendor import _convert_request -from ...operations._return_operations_operations import build_post_request -from .._vendor import AzureReservationAPIMixinABC - -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 ReturnOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.aio.AzureReservationAPI`'s - :attr:`return_operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - async def _post_initial( - self, reservation_order_id: str, body: Union[_models.RefundRequest, IO], **kwargs: Any - ) -> Union[_models.ReservationOrderResponse, _models.RefundResponse]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Union[_models.ReservationOrderResponse, _models.RefundResponse]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "RefundRequest") - - request = build_post_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._post_initial.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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("RefundResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return"} - - @overload - async def begin_post( - self, - reservation_order_id: str, - body: _models.RefundRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationOrderResponse]: - """Return a reservation. - - Return a reservation and get refund information. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for returning reservation. Required. - :type body: ~azure.mgmt.reservations.models.RefundRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationOrderResponse or An - instance of AsyncLROPoller that returns either RefundResponse or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.RefundResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_post( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationOrderResponse]: - """Return a reservation. - - Return a reservation and get refund information. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for returning reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationOrderResponse or An - instance of AsyncLROPoller that returns either RefundResponse or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.RefundResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_post( - self, reservation_order_id: str, body: Union[_models.RefundRequest, IO], **kwargs: Any - ) -> AsyncLROPoller[_models.ReservationOrderResponse]: - """Return a reservation. - - Return a reservation and get refund information. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for returning reservation. Is either a RefundRequest type or a - IO type. Required. - :type body: ~azure.mgmt.reservations.models.RefundRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either ReservationOrderResponse or An - instance of AsyncLROPoller that returns either RefundResponse or the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] or - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.reservations.models.RefundResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationOrderResponse] = 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._post_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py index 1d4db29e5dbc..25f4cf71fa5d 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/__init__.py @@ -2,146 +2,147 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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 AppliedReservationList -from ._models_py3 import AppliedReservations -from ._models_py3 import AppliedScopeProperties -from ._models_py3 import AvailableScopeProperties -from ._models_py3 import AvailableScopeRequest -from ._models_py3 import AvailableScopeRequestProperties -from ._models_py3 import BillingInformation -from ._models_py3 import CalculateExchangeOperationResultResponse -from ._models_py3 import CalculateExchangeRequest -from ._models_py3 import CalculateExchangeRequestProperties -from ._models_py3 import CalculateExchangeResponseProperties -from ._models_py3 import CalculatePriceResponse -from ._models_py3 import CalculatePriceResponseProperties -from ._models_py3 import CalculatePriceResponsePropertiesBillingCurrencyTotal -from ._models_py3 import CalculatePriceResponsePropertiesPricingCurrencyTotal -from ._models_py3 import CalculateRefundRequest -from ._models_py3 import CalculateRefundRequestProperties -from ._models_py3 import CalculateRefundResponse -from ._models_py3 import Catalog -from ._models_py3 import CatalogMsrp -from ._models_py3 import CatalogsResult -from ._models_py3 import ChangeDirectoryRequest -from ._models_py3 import ChangeDirectoryResponse -from ._models_py3 import ChangeDirectoryResult -from ._models_py3 import Commitment -from ._models_py3 import CreateGenericQuotaRequestParameters -from ._models_py3 import CurrentQuotaLimit -from ._models_py3 import CurrentQuotaLimitBase -from ._models_py3 import Error -from ._models_py3 import ErrorDetails -from ._models_py3 import ErrorResponse -from ._models_py3 import ExceptionResponse -from ._models_py3 import ExchangeOperationResultResponse -from ._models_py3 import ExchangePolicyError -from ._models_py3 import ExchangePolicyErrors -from ._models_py3 import ExchangeRequest -from ._models_py3 import ExchangeRequestProperties -from ._models_py3 import ExchangeResponseProperties -from ._models_py3 import ExtendedErrorInfo -from ._models_py3 import ExtendedStatusInfo -from ._models_py3 import MergeRequest -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationList -from ._models_py3 import OperationResponse -from ._models_py3 import OperationResultError -from ._models_py3 import Patch -from ._models_py3 import PatchPropertiesRenewProperties -from ._models_py3 import PaymentDetail -from ._models_py3 import Price -from ._models_py3 import ProxyResource -from ._models_py3 import PurchaseRequest -from ._models_py3 import PurchaseRequestPropertiesReservedResourceProperties -from ._models_py3 import QuotaLimits -from ._models_py3 import QuotaLimitsResponse -from ._models_py3 import QuotaProperties -from ._models_py3 import QuotaRequestDetails -from ._models_py3 import QuotaRequestDetailsList -from ._models_py3 import QuotaRequestOneResourceSubmitResponse -from ._models_py3 import QuotaRequestProperties -from ._models_py3 import QuotaRequestSubmitResponse -from ._models_py3 import QuotaRequestSubmitResponse201 -from ._models_py3 import RefundBillingInformation -from ._models_py3 import RefundPolicyError -from ._models_py3 import RefundPolicyResult -from ._models_py3 import RefundPolicyResultProperty -from ._models_py3 import RefundRequest -from ._models_py3 import RefundRequestProperties -from ._models_py3 import RefundResponse -from ._models_py3 import RefundResponseProperties -from ._models_py3 import RenewPropertiesResponse -from ._models_py3 import RenewPropertiesResponseBillingCurrencyTotal -from ._models_py3 import RenewPropertiesResponsePricingCurrencyTotal -from ._models_py3 import ReservationList -from ._models_py3 import ReservationMergeProperties -from ._models_py3 import ReservationOrderBillingPlanInformation -from ._models_py3 import ReservationOrderList -from ._models_py3 import ReservationOrderResponse -from ._models_py3 import ReservationResponse -from ._models_py3 import ReservationSplitProperties -from ._models_py3 import ReservationSummary -from ._models_py3 import ReservationSwapProperties -from ._models_py3 import ReservationToExchange -from ._models_py3 import ReservationToPurchaseCalculateExchange -from ._models_py3 import ReservationToPurchaseExchange -from ._models_py3 import ReservationToReturn -from ._models_py3 import ReservationToReturnForExchange -from ._models_py3 import ReservationUtilizationAggregates -from ._models_py3 import ReservationsListResult -from ._models_py3 import ReservationsProperties -from ._models_py3 import ReservationsPropertiesUtilization -from ._models_py3 import Resource -from ._models_py3 import ResourceName -from ._models_py3 import SavingsPlanPurchaseRequest -from ._models_py3 import SavingsPlanToPurchaseCalculateExchange -from ._models_py3 import SavingsPlanToPurchaseExchange -from ._models_py3 import ScopeProperties -from ._models_py3 import ServiceError -from ._models_py3 import ServiceErrorDetail -from ._models_py3 import SkuCapability -from ._models_py3 import SkuName -from ._models_py3 import SkuProperty -from ._models_py3 import SkuRestriction -from ._models_py3 import SplitRequest -from ._models_py3 import SubRequest -from ._models_py3 import SubscriptionScopeProperties -from ._models_py3 import SystemData +from typing import TYPE_CHECKING -from ._azure_reservation_api_enums import AppliedScopeType -from ._azure_reservation_api_enums import BillingPlan -from ._azure_reservation_api_enums import CalculateExchangeOperationResultStatus -from ._azure_reservation_api_enums import CommitmentGrain -from ._azure_reservation_api_enums import CreatedByType -from ._azure_reservation_api_enums import DisplayProvisioningState -from ._azure_reservation_api_enums import ErrorResponseCode -from ._azure_reservation_api_enums import ExchangeOperationResultStatus -from ._azure_reservation_api_enums import InstanceFlexibility -from ._azure_reservation_api_enums import Location -from ._azure_reservation_api_enums import OperationStatus -from ._azure_reservation_api_enums import PaymentStatus -from ._azure_reservation_api_enums import ProvisioningState -from ._azure_reservation_api_enums import QuotaRequestState -from ._azure_reservation_api_enums import ReservationBillingPlan -from ._azure_reservation_api_enums import ReservationStatusCode -from ._azure_reservation_api_enums import ReservationTerm -from ._azure_reservation_api_enums import ReservedResourceType -from ._azure_reservation_api_enums import ResourceType -from ._azure_reservation_api_enums import SavingsPlanTerm -from ._azure_reservation_api_enums import UserFriendlyAppliedScopeType -from ._azure_reservation_api_enums import UserFriendlyRenewState +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AppliedReservationList, + AppliedReservations, + AppliedReservationsProperties, + AppliedScopeProperties, + AvailableScopeProperties, + AvailableScopeRequest, + AvailableScopeRequestProperties, + BillingInformation, + CalculateExchangeOperationResultResponse, + CalculateExchangeRequest, + CalculateExchangeRequestProperties, + CalculateExchangeResponseProperties, + CalculatePriceResponse, + CalculatePriceResponseProperties, + CalculatePriceResponsePropertiesBillingCurrencyTotal, + CalculatePriceResponsePropertiesPricingCurrencyTotal, + CalculateRefundRequest, + CalculateRefundRequestProperties, + CalculateRefundResponse, + Catalog, + CatalogMsrp, + ChangeDirectoryRequest, + ChangeDirectoryResponse, + ChangeDirectoryResult, + Commitment, + CurrentQuotaLimitBase, + Error, + ErrorDetails, + ErrorResponse, + ExceptionResponse, + ExchangeOperationResultResponse, + ExchangePolicyError, + ExchangePolicyErrors, + ExchangeRequest, + ExchangeRequestProperties, + ExchangeResponseProperties, + ExtendedErrorInfo, + ExtendedStatusInfo, + MergeProperties, + MergeRequest, + OperationDisplay, + OperationResponse, + OperationResultError, + Patch, + PatchProperties, + PatchPropertiesRenewProperties, + PaymentDetail, + Price, + ProxyResource, + PurchaseRequest, + PurchaseRequestProperties, + PurchaseRequestPropertiesReservedResourceProperties, + QuotaProperties, + QuotaRequestDetails, + QuotaRequestProperties, + RefundBillingInformation, + RefundPolicyError, + RefundPolicyResult, + RefundPolicyResultProperty, + RefundRequest, + RefundRequestProperties, + RefundResponseProperties, + RenewPropertiesResponse, + RenewPropertiesResponseBillingCurrencyTotal, + RenewPropertiesResponsePricingCurrencyTotal, + ReservationMergeProperties, + ReservationOrderBillingPlanInformation, + ReservationOrderProperties, + ReservationOrderResponse, + ReservationResponse, + ReservationSplitProperties, + ReservationSummary, + ReservationSwapProperties, + ReservationToExchange, + ReservationToPurchaseCalculateExchange, + ReservationToPurchaseExchange, + ReservationToReturn, + ReservationToReturnForExchange, + ReservationUtilizationAggregates, + ReservationsProperties, + ReservationsPropertiesUtilization, + Resource, + ResourceName, + SavingsPlanPurchaseRequest, + SavingsPlanPurchaseRequestProperties, + SavingsPlanToPurchaseCalculateExchange, + SavingsPlanToPurchaseExchange, + ScopeProperties, + ServiceError, + ServiceErrorDetail, + SkuCapability, + SkuName, + SkuProperty, + SkuRestriction, + SplitProperties, + SplitRequest, + SubRequest, + SubscriptionScopeProperties, + SystemData, +) + +from ._enums import ( # type: ignore + AppliedScopeType, + BillingPlan, + CalculateExchangeOperationResultStatus, + CommitmentGrain, + CreatedByType, + ErrorResponseCode, + ExchangeOperationResultStatus, + InstanceFlexibility, + OperationStatus, + PaymentStatus, + ProvisioningState, + QuotaRequestState, + ReservationBillingPlan, + ReservationStatusCode, + ReservationTerm, + ReservedResourceType, + ResourceType, + SavingsPlanTerm, +) 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__ = [ "AppliedReservationList", "AppliedReservations", + "AppliedReservationsProperties", "AppliedScopeProperties", "AvailableScopeProperties", "AvailableScopeRequest", @@ -160,13 +161,10 @@ "CalculateRefundResponse", "Catalog", "CatalogMsrp", - "CatalogsResult", "ChangeDirectoryRequest", "ChangeDirectoryResponse", "ChangeDirectoryResult", "Commitment", - "CreateGenericQuotaRequestParameters", - "CurrentQuotaLimit", "CurrentQuotaLimitBase", "Error", "ErrorDetails", @@ -180,42 +178,36 @@ "ExchangeResponseProperties", "ExtendedErrorInfo", "ExtendedStatusInfo", + "MergeProperties", "MergeRequest", "OperationDisplay", - "OperationList", "OperationResponse", "OperationResultError", "Patch", + "PatchProperties", "PatchPropertiesRenewProperties", "PaymentDetail", "Price", "ProxyResource", "PurchaseRequest", + "PurchaseRequestProperties", "PurchaseRequestPropertiesReservedResourceProperties", - "QuotaLimits", - "QuotaLimitsResponse", "QuotaProperties", "QuotaRequestDetails", - "QuotaRequestDetailsList", - "QuotaRequestOneResourceSubmitResponse", "QuotaRequestProperties", - "QuotaRequestSubmitResponse", - "QuotaRequestSubmitResponse201", "RefundBillingInformation", "RefundPolicyError", "RefundPolicyResult", "RefundPolicyResultProperty", "RefundRequest", "RefundRequestProperties", - "RefundResponse", "RefundResponseProperties", "RenewPropertiesResponse", "RenewPropertiesResponseBillingCurrencyTotal", "RenewPropertiesResponsePricingCurrencyTotal", - "ReservationList", "ReservationMergeProperties", "ReservationOrderBillingPlanInformation", - "ReservationOrderList", + "ReservationOrderProperties", "ReservationOrderResponse", "ReservationResponse", "ReservationSplitProperties", @@ -227,12 +219,12 @@ "ReservationToReturn", "ReservationToReturnForExchange", "ReservationUtilizationAggregates", - "ReservationsListResult", "ReservationsProperties", "ReservationsPropertiesUtilization", "Resource", "ResourceName", "SavingsPlanPurchaseRequest", + "SavingsPlanPurchaseRequestProperties", "SavingsPlanToPurchaseCalculateExchange", "SavingsPlanToPurchaseExchange", "ScopeProperties", @@ -242,6 +234,7 @@ "SkuName", "SkuProperty", "SkuRestriction", + "SplitProperties", "SplitRequest", "SubRequest", "SubscriptionScopeProperties", @@ -251,11 +244,9 @@ "CalculateExchangeOperationResultStatus", "CommitmentGrain", "CreatedByType", - "DisplayProvisioningState", "ErrorResponseCode", "ExchangeOperationResultStatus", "InstanceFlexibility", - "Location", "OperationStatus", "PaymentStatus", "ProvisioningState", @@ -266,8 +257,6 @@ "ReservedResourceType", "ResourceType", "SavingsPlanTerm", - "UserFriendlyAppliedScopeType", - "UserFriendlyRenewState", ] -__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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_azure_reservation_api_enums.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_enums.py similarity index 66% rename from sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_azure_reservation_api_enums.py rename to sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_enums.py index a384a3971088..ff6d1a9f7336 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_azure_reservation_api_enums.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_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,125 +14,187 @@ class AppliedScopeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of the Applied Scope.""" SINGLE = "Single" + """Single.""" SHARED = "Shared" + """Shared.""" MANAGEMENT_GROUP = "ManagementGroup" + """ManagementGroup.""" class BillingPlan(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represents the billing plan in ISO 8601 format. Required only for monthly billing plans.""" P1_M = "P1M" + """P1M.""" class CalculateExchangeOperationResultStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Status of the operation.""" SUCCEEDED = "Succeeded" + """Succeeded.""" FAILED = "Failed" + """Failed.""" CANCELLED = "Cancelled" + """Cancelled.""" PENDING = "Pending" + """Pending.""" class CommitmentGrain(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Commitment grain.""" HOURLY = "Hourly" + """Hourly.""" class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of identity that created the resource.""" + """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" - - -class DisplayProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Represent the current display state of the reservation.""" - - SUCCEEDED = "Succeeded" - EXPIRING = "Expiring" - EXPIRED = "Expired" - PENDING = "Pending" - PROCESSING = "Processing" - CANCELLED = "Cancelled" - FAILED = "Failed" - WARNING = "Warning" - NO_BENEFIT = "NoBenefit" + """The entity was created by a key.""" class ErrorResponseCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Error code describing the reason that service is not able to process the incoming request.""" NOT_SPECIFIED = "NotSpecified" + """NotSpecified.""" INTERNAL_SERVER_ERROR = "InternalServerError" + """InternalServerError.""" SERVER_TIMEOUT = "ServerTimeout" + """ServerTimeout.""" AUTHORIZATION_FAILED = "AuthorizationFailed" + """AuthorizationFailed.""" BAD_REQUEST = "BadRequest" + """BadRequest.""" CLIENT_CERTIFICATE_THUMBPRINT_NOT_SET = "ClientCertificateThumbprintNotSet" + """ClientCertificateThumbprintNotSet.""" INVALID_REQUEST_CONTENT = "InvalidRequestContent" + """InvalidRequestContent.""" OPERATION_FAILED = "OperationFailed" + """OperationFailed.""" HTTP_METHOD_NOT_SUPPORTED = "HttpMethodNotSupported" + """HttpMethodNotSupported.""" INVALID_REQUEST_URI = "InvalidRequestUri" + """InvalidRequestUri.""" MISSING_TENANT_ID = "MissingTenantId" + """MissingTenantId.""" INVALID_TENANT_ID = "InvalidTenantId" + """InvalidTenantId.""" INVALID_RESERVATION_ORDER_ID = "InvalidReservationOrderId" + """InvalidReservationOrderId.""" INVALID_RESERVATION_ID = "InvalidReservationId" + """InvalidReservationId.""" RESERVATION_ID_NOT_IN_RESERVATION_ORDER = "ReservationIdNotInReservationOrder" + """ReservationIdNotInReservationOrder.""" RESERVATION_ORDER_NOT_FOUND = "ReservationOrderNotFound" + """ReservationOrderNotFound.""" INVALID_SUBSCRIPTION_ID = "InvalidSubscriptionId" + """InvalidSubscriptionId.""" INVALID_ACCESS_TOKEN = "InvalidAccessToken" + """InvalidAccessToken.""" INVALID_LOCATION_ID = "InvalidLocationId" + """InvalidLocationId.""" UNAUTHENTICATED_REQUESTS_THROTTLED = "UnauthenticatedRequestsThrottled" + """UnauthenticatedRequestsThrottled.""" INVALID_HEALTH_CHECK_TYPE = "InvalidHealthCheckType" + """InvalidHealthCheckType.""" FORBIDDEN = "Forbidden" + """Forbidden.""" BILLING_SCOPE_ID_CANNOT_BE_CHANGED = "BillingScopeIdCannotBeChanged" + """BillingScopeIdCannotBeChanged.""" APPLIED_SCOPES_NOT_ASSOCIATED_WITH_COMMERCE_ACCOUNT = "AppliedScopesNotAssociatedWithCommerceAccount" + """AppliedScopesNotAssociatedWithCommerceAccount.""" PATCH_VALUES_SAME_AS_EXISTING = "PatchValuesSameAsExisting" + """PatchValuesSameAsExisting.""" ROLE_ASSIGNMENT_CREATION_FAILED = "RoleAssignmentCreationFailed" + """RoleAssignmentCreationFailed.""" RESERVATION_ORDER_CREATION_FAILED = "ReservationOrderCreationFailed" + """ReservationOrderCreationFailed.""" RESERVATION_ORDER_NOT_ENABLED = "ReservationOrderNotEnabled" + """ReservationOrderNotEnabled.""" CAPACITY_UPDATE_SCOPES_FAILED = "CapacityUpdateScopesFailed" + """CapacityUpdateScopesFailed.""" UNSUPPORTED_RESERVATION_TERM = "UnsupportedReservationTerm" + """UnsupportedReservationTerm.""" RESERVATION_ORDER_ID_ALREADY_EXISTS = "ReservationOrderIdAlreadyExists" + """ReservationOrderIdAlreadyExists.""" RISK_CHECK_FAILED = "RiskCheckFailed" + """RiskCheckFailed.""" CREATE_QUOTE_FAILED = "CreateQuoteFailed" + """CreateQuoteFailed.""" ACTIVATE_QUOTE_FAILED = "ActivateQuoteFailed" + """ActivateQuoteFailed.""" NONSUPPORTED_ACCOUNT_ID = "NonsupportedAccountId" + """NonsupportedAccountId.""" PAYMENT_INSTRUMENT_NOT_FOUND = "PaymentInstrumentNotFound" + """PaymentInstrumentNotFound.""" MISSING_APPLIED_SCOPES_FOR_SINGLE = "MissingAppliedScopesForSingle" + """MissingAppliedScopesForSingle.""" NO_VALID_RESERVATIONS_TO_RE_RATE = "NoValidReservationsToReRate" + """NoValidReservationsToReRate.""" RE_RATE_ONLY_ALLOWED_FOR_EA = "ReRateOnlyAllowedForEA" + """ReRateOnlyAllowedForEA.""" OPERATION_CANNOT_BE_PERFORMED_IN_CURRENT_STATE = "OperationCannotBePerformedInCurrentState" + """OperationCannotBePerformedInCurrentState.""" INVALID_SINGLE_APPLIED_SCOPES_COUNT = "InvalidSingleAppliedScopesCount" + """InvalidSingleAppliedScopesCount.""" INVALID_FULFILLMENT_REQUEST_PARAMETERS = "InvalidFulfillmentRequestParameters" + """InvalidFulfillmentRequestParameters.""" NOT_SUPPORTED_COUNTRY = "NotSupportedCountry" + """NotSupportedCountry.""" INVALID_REFUND_QUANTITY = "InvalidRefundQuantity" + """InvalidRefundQuantity.""" PURCHASE_ERROR = "PurchaseError" + """PurchaseError.""" BILLING_CUSTOMER_INPUT_ERROR = "BillingCustomerInputError" + """BillingCustomerInputError.""" BILLING_PAYMENT_INSTRUMENT_SOFT_ERROR = "BillingPaymentInstrumentSoftError" + """BillingPaymentInstrumentSoftError.""" BILLING_PAYMENT_INSTRUMENT_HARD_ERROR = "BillingPaymentInstrumentHardError" + """BillingPaymentInstrumentHardError.""" BILLING_TRANSIENT_ERROR = "BillingTransientError" + """BillingTransientError.""" BILLING_ERROR = "BillingError" + """BillingError.""" FULFILLMENT_CONFIGURATION_ERROR = "FulfillmentConfigurationError" + """FulfillmentConfigurationError.""" FULFILLMENT_OUT_OF_STOCK_ERROR = "FulfillmentOutOfStockError" + """FulfillmentOutOfStockError.""" FULFILLMENT_TRANSIENT_ERROR = "FulfillmentTransientError" + """FulfillmentTransientError.""" FULFILLMENT_ERROR = "FulfillmentError" + """FulfillmentError.""" CALCULATE_PRICE_FAILED = "CalculatePriceFailed" + """CalculatePriceFailed.""" APPLIED_SCOPES_SAME_AS_EXISTING = "AppliedScopesSameAsExisting" + """AppliedScopesSameAsExisting.""" SELF_SERVICE_REFUND_NOT_SUPPORTED = "SelfServiceRefundNotSupported" + """SelfServiceRefundNotSupported.""" REFUND_LIMIT_EXCEEDED = "RefundLimitExceeded" + """RefundLimitExceeded.""" class ExchangeOperationResultStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Status of the operation.""" SUCCEEDED = "Succeeded" + """Succeeded.""" FAILED = "Failed" + """Failed.""" CANCELLED = "Cancelled" + """Cancelled.""" PENDING_REFUNDS = "PendingRefunds" + """PendingRefunds.""" PENDING_PURCHASES = "PendingPurchases" + """PendingPurchases.""" class InstanceFlexibility(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -141,179 +203,206 @@ class InstanceFlexibility(str, Enum, metaclass=CaseInsensitiveEnumMeta): """ ON = "On" + """On.""" OFF = "Off" - - -class Location(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Location in which the Resources needs to be reserved. It cannot be changed after the resource - has been created. - """ - - WESTUS = "westus" - EASTUS = "eastus" - EASTUS2 = "eastus2" - NORTHCENTRALUS = "northcentralus" - WESTUS2 = "westus2" - SOUTHCENTRALUS = "southcentralus" - CENTRALUS = "centralus" - WESTEUROPE = "westeurope" - NORTHEUROPE = "northeurope" - EASTASIA = "eastasia" - SOUTHEASTASIA = "southeastasia" - JAPANEAST = "japaneast" - JAPANWEST = "japanwest" - BRAZILSOUTH = "brazilsouth" - AUSTRALIAEAST = "australiaeast" - AUSTRALIASOUTHEAST = "australiasoutheast" - SOUTHINDIA = "southindia" - WESTINDIA = "westindia" - CENTRALINDIA = "centralindia" - CANADACENTRAL = "canadacentral" - CANADAEAST = "canadaeast" - UKSOUTH = "uksouth" - WESTCENTRALUS = "westcentralus" - UKWEST = "ukwest" + """Off.""" class OperationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Status of the individual operation.""" SUCCEEDED = "Succeeded" + """Succeeded.""" FAILED = "Failed" + """Failed.""" CANCELLED = "Cancelled" + """Cancelled.""" PENDING = "Pending" + """Pending.""" class PaymentStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Describes whether the payment is completed, failed, cancelled or scheduled in the future.""" SUCCEEDED = "Succeeded" + """Succeeded.""" FAILED = "Failed" + """Failed.""" SCHEDULED = "Scheduled" + """Scheduled.""" CANCELLED = "Cancelled" + """Cancelled.""" class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represent the current state of the Reservation.""" CREATING = "Creating" + """Creating.""" PENDING_RESOURCE_HOLD = "PendingResourceHold" + """PendingResourceHold.""" CONFIRMED_RESOURCE_HOLD = "ConfirmedResourceHold" + """ConfirmedResourceHold.""" PENDING_BILLING = "PendingBilling" + """PendingBilling.""" CONFIRMED_BILLING = "ConfirmedBilling" + """ConfirmedBilling.""" CREATED = "Created" + """Created.""" SUCCEEDED = "Succeeded" + """Succeeded.""" CANCELLED = "Cancelled" + """Cancelled.""" EXPIRED = "Expired" + """Expired.""" BILLING_FAILED = "BillingFailed" + """BillingFailed.""" FAILED = "Failed" + """Failed.""" SPLIT = "Split" + """Split.""" MERGED = "Merged" + """Merged.""" class QuotaRequestState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The quota request status.""" ACCEPTED = "Accepted" + """Accepted.""" INVALID = "Invalid" + """Invalid.""" SUCCEEDED = "Succeeded" + """Succeeded.""" FAILED = "Failed" + """Failed.""" IN_PROGRESS = "InProgress" + """InProgress.""" class ReservationBillingPlan(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represent the billing plans.""" UPFRONT = "Upfront" + """Upfront.""" MONTHLY = "Monthly" + """Monthly.""" class ReservationStatusCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ReservationStatusCode.""" + """Type of ReservationStatusCode.""" NONE = "None" + """None.""" PENDING = "Pending" + """Pending.""" PROCESSING = "Processing" + """Processing.""" ACTIVE = "Active" + """Active.""" PURCHASE_ERROR = "PurchaseError" + """PurchaseError.""" PAYMENT_INSTRUMENT_ERROR = "PaymentInstrumentError" + """PaymentInstrumentError.""" SPLIT = "Split" + """Split.""" MERGED = "Merged" + """Merged.""" EXPIRED = "Expired" + """Expired.""" SUCCEEDED = "Succeeded" + """Succeeded.""" class ReservationTerm(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represent the term of reservation.""" P1_Y = "P1Y" + """P1Y.""" P3_Y = "P3Y" + """P3Y.""" P5_Y = "P5Y" + """P5Y.""" class ReservedResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of the resource that is being reserved.""" + """The type of the resource that is being reserved. In addition to below types we have also added + the following: OpenAIPTU, MDC, Sentinel. + """ VIRTUAL_MACHINES = "VirtualMachines" + """VirtualMachines.""" SQL_DATABASES = "SqlDatabases" + """SqlDatabases.""" SUSE_LINUX = "SuseLinux" + """SuseLinux.""" COSMOS_DB = "CosmosDb" + """CosmosDb.""" RED_HAT = "RedHat" + """RedHat.""" SQL_DATA_WAREHOUSE = "SqlDataWarehouse" + """SqlDataWarehouse.""" V_MWARE_CLOUD_SIMPLE = "VMwareCloudSimple" + """VMwareCloudSimple.""" RED_HAT_OSA = "RedHatOsa" + """RedHatOsa.""" DATABRICKS = "Databricks" + """Databricks.""" APP_SERVICE = "AppService" + """AppService.""" MANAGED_DISK = "ManagedDisk" + """ManagedDisk.""" BLOCK_BLOB = "BlockBlob" + """BlockBlob.""" REDIS_CACHE = "RedisCache" + """RedisCache.""" AZURE_DATA_EXPLORER = "AzureDataExplorer" + """AzureDataExplorer.""" MY_SQL = "MySql" + """MySql.""" MARIA_DB = "MariaDb" + """MariaDb.""" POSTGRE_SQL = "PostgreSql" + """PostgreSql.""" DEDICATED_HOST = "DedicatedHost" + """DedicatedHost.""" SAP_HANA = "SapHana" + """SapHana.""" SQL_AZURE_HYBRID_BENEFIT = "SqlAzureHybridBenefit" + """SqlAzureHybridBenefit.""" AVS = "AVS" + """AVS.""" DATA_FACTORY = "DataFactory" + """DataFactory.""" NET_APP_STORAGE = "NetAppStorage" + """NetAppStorage.""" AZURE_FILES = "AzureFiles" + """AzureFiles.""" SQL_EDGE = "SqlEdge" + """SqlEdge.""" VIRTUAL_MACHINE_SOFTWARE = "VirtualMachineSoftware" + """VirtualMachineSoftware.""" class ResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The resource types.""" STANDARD = "standard" + """standard.""" DEDICATED = "dedicated" + """dedicated.""" LOW_PRIORITY = "lowPriority" + """lowPriority.""" SHARED = "shared" + """shared.""" SERVICE_SPECIFIC = "serviceSpecific" + """serviceSpecific.""" class SavingsPlanTerm(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represent savings plan term in ISO 8601 format.""" P1_Y = "P1Y" + """P1Y.""" P3_Y = "P3Y" - - -class UserFriendlyAppliedScopeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The applied scope type.""" - - NONE = "None" - SHARED = "Shared" - SINGLE = "Single" - RESOURCE_GROUP = "ResourceGroup" - MANAGEMENT_GROUP = "ManagementGroup" - - -class UserFriendlyRenewState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The renew state of the reservation.""" - - ON = "On" - OFF = "Off" - RENEWED = "Renewed" - NOT_RENEWED = "NotRenewed" - NOT_APPLICABLE = "NotApplicable" + """P3Y.""" diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models.py new file mode 100644 index 000000000000..1b903a0a509c --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models.py @@ -0,0 +1,4868 @@ +# 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 +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class AppliedReservationList(_Model): + """Paginated list of applied reservations. + + :ivar value: Array of reservation resource ids. + :vartype value: list[str] + :ivar next_link: Url to get the next page of reservations. + :vartype next_link: str + """ + + value: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Array of reservation resource ids.""" + next_link: Optional[str] = rest_field(name="nextLink", visibility=["read", "create", "update", "delete", "query"]) + """Url to get the next page of reservations.""" + + @overload + def __init__( + self, + *, + value: Optional[list[str]] = None, + next_link: 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 AppliedReservations(_Model): + """The response for applied reservations api. + + :ivar id: Identifier of the applied reservations. + :vartype id: str + :ivar name: Name of resource. + :vartype name: str + :ivar type: Type of resource. "Microsoft.Capacity/AppliedReservations". + :vartype type: str + :ivar properties: Properties for applied reservations returned. + :vartype properties: ~azure.mgmt.reservations.models.AppliedReservationsProperties + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Identifier of the applied reservations.""" + name: Optional[str] = rest_field(visibility=["read"]) + """Name of resource.""" + type: Optional[str] = rest_field(visibility=["read"]) + """Type of resource. \"Microsoft.Capacity/AppliedReservations\".""" + properties: Optional["_models.AppliedReservationsProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for applied reservations returned.""" + + __flattened_items = ["reservation_order_ids"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.AppliedReservationsProperties"] = 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 AppliedReservationsProperties(_Model): + """Properties for applied reservations returned. + + :ivar reservation_order_ids: Paginated list of applied reservations. + :vartype reservation_order_ids: ~azure.mgmt.reservations.models.AppliedReservationList + """ + + reservation_order_ids: Optional["_models.AppliedReservationList"] = rest_field( + name="reservationOrderIds", visibility=["read", "create", "update", "delete", "query"] + ) + """Paginated list of applied reservations.""" + + @overload + def __init__( + self, + *, + reservation_order_ids: Optional["_models.AppliedReservationList"] = 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 AppliedScopeProperties(_Model): + """Properties specific to applied scope type. Not required if not applicable. Required and need to + provide tenantId and managementGroupId if AppliedScopeType is ManagementGroup. + + :ivar tenant_id: Tenant ID where the savings plan should apply benefit. + :vartype tenant_id: str + :ivar management_group_id: Fully-qualified identifier of the management group where the benefit + must be applied. + :vartype management_group_id: str + :ivar subscription_id: Fully-qualified identifier of the subscription. + :vartype subscription_id: str + :ivar resource_group_id: Fully-qualified identifier of the resource group. + :vartype resource_group_id: str + :ivar display_name: Display name. + :vartype display_name: str + """ + + tenant_id: Optional[str] = rest_field(name="tenantId", visibility=["read", "create", "update", "delete", "query"]) + """Tenant ID where the savings plan should apply benefit.""" + management_group_id: Optional[str] = rest_field( + name="managementGroupId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully-qualified identifier of the management group where the benefit must be applied.""" + subscription_id: Optional[str] = rest_field( + name="subscriptionId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully-qualified identifier of the subscription.""" + resource_group_id: Optional[str] = rest_field( + name="resourceGroupId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully-qualified identifier of the resource group.""" + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """Display name.""" + + @overload + def __init__( + self, + *, + tenant_id: Optional[str] = None, + management_group_id: Optional[str] = None, + subscription_id: Optional[str] = None, + resource_group_id: Optional[str] = None, + display_name: 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 AvailableScopeProperties(_Model): + """The response of available scope api containing scopes and their eligibilities. + + :ivar properties: The scopes checked by the available scope api. + :vartype properties: ~azure.mgmt.reservations.models.SubscriptionScopeProperties + """ + + properties: Optional["_models.SubscriptionScopeProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The scopes checked by the available scope api.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.SubscriptionScopeProperties"] = 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 AvailableScopeRequest(_Model): + """Available scope. + + :ivar properties: Available scope request properties. + :vartype properties: ~azure.mgmt.reservations.models.AvailableScopeRequestProperties + """ + + properties: Optional["_models.AvailableScopeRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Available scope request properties.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.AvailableScopeRequestProperties"] = 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 AvailableScopeRequestProperties(_Model): + """Available scope request properties. + + :ivar scopes: + :vartype scopes: list[str] + """ + + scopes: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + scopes: 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 BillingInformation(_Model): + """billing information. + + :ivar billing_currency_total_paid_amount: Pricing information containing the amount and the + currency code. + :vartype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_currency_prorated_amount: Pricing information containing the amount and the + currency code. + :vartype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_currency_remaining_commitment_amount: Pricing information containing the amount + and the currency code. + :vartype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price + """ + + billing_currency_total_paid_amount: Optional["_models.Price"] = rest_field( + name="billingCurrencyTotalPaidAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + billing_currency_prorated_amount: Optional["_models.Price"] = rest_field( + name="billingCurrencyProratedAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + billing_currency_remaining_commitment_amount: Optional["_models.Price"] = rest_field( + name="billingCurrencyRemainingCommitmentAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + + @overload + def __init__( + self, + *, + billing_currency_total_paid_amount: Optional["_models.Price"] = None, + billing_currency_prorated_amount: Optional["_models.Price"] = None, + billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None, + ) -> 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 CalculateExchangeOperationResultResponse(_Model): + """CalculateExchange operation result. + + :ivar id: It should match what is used to GET the operation result. + :vartype id: str + :ivar name: It must match the last segment of the id field, and will typically be a GUID / + system generated value. + :vartype name: str + :ivar status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", + and "Pending". + :vartype status: str or ~azure.mgmt.reservations.models.CalculateExchangeOperationResultStatus + :ivar properties: CalculateExchange response properties. + :vartype properties: ~azure.mgmt.reservations.models.CalculateExchangeResponseProperties + :ivar error: Required if status == failed or status == canceled. + :vartype error: ~azure.mgmt.reservations.models.OperationResultError + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """It should match what is used to GET the operation result.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """It must match the last segment of the id field, and will typically be a GUID / system generated + value.""" + status: Optional[Union[str, "_models.CalculateExchangeOperationResultStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Status of the operation. Known values are: \"Succeeded\", \"Failed\", \"Cancelled\", and + \"Pending\".""" + properties: Optional["_models.CalculateExchangeResponseProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """CalculateExchange response properties.""" + error: Optional["_models.OperationResultError"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Required if status == failed or status == canceled.""" + + @overload + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + status: Optional[Union[str, "_models.CalculateExchangeOperationResultStatus"]] = None, + properties: Optional["_models.CalculateExchangeResponseProperties"] = None, + error: Optional["_models.OperationResultError"] = 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 CalculateExchangeRequest(_Model): + """Calculate exchange request. + + :ivar properties: Calculate exchange request properties. + :vartype properties: ~azure.mgmt.reservations.models.CalculateExchangeRequestProperties + """ + + properties: Optional["_models.CalculateExchangeRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Calculate exchange request properties.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.CalculateExchangeRequestProperties"] = 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 CalculateExchangeRequestProperties(_Model): + """Calculate exchange request properties. + + :ivar reservations_to_purchase: List of reservations that are being purchased in this exchange. + :vartype reservations_to_purchase: list[~azure.mgmt.reservations.models.PurchaseRequest] + :ivar savings_plans_to_purchase: List of savings plans that are being purchased in this + exchange. + :vartype savings_plans_to_purchase: + list[~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest] + :ivar reservations_to_exchange: List of reservations that are being returned in this exchange. + :vartype reservations_to_exchange: list[~azure.mgmt.reservations.models.ReservationToReturn] + """ + + reservations_to_purchase: Optional[list["_models.PurchaseRequest"]] = rest_field( + name="reservationsToPurchase", visibility=["read", "create", "update", "delete", "query"] + ) + """List of reservations that are being purchased in this exchange.""" + savings_plans_to_purchase: Optional[list["_models.SavingsPlanPurchaseRequest"]] = rest_field( + name="savingsPlansToPurchase", visibility=["read", "create", "update", "delete", "query"] + ) + """List of savings plans that are being purchased in this exchange.""" + reservations_to_exchange: Optional[list["_models.ReservationToReturn"]] = rest_field( + name="reservationsToExchange", visibility=["read", "create", "update", "delete", "query"] + ) + """List of reservations that are being returned in this exchange.""" + + @overload + def __init__( + self, + *, + reservations_to_purchase: Optional[list["_models.PurchaseRequest"]] = None, + savings_plans_to_purchase: Optional[list["_models.SavingsPlanPurchaseRequest"]] = None, + reservations_to_exchange: Optional[list["_models.ReservationToReturn"]] = 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 CalculateExchangeResponseProperties(_Model): + """CalculateExchange response properties. + + :ivar session_id: Exchange session identifier. + :vartype session_id: str + :ivar net_payable: Pricing information containing the amount and the currency code. + :vartype net_payable: ~azure.mgmt.reservations.models.Price + :ivar refunds_total: Pricing information containing the amount and the currency code. + :vartype refunds_total: ~azure.mgmt.reservations.models.Price + :ivar purchases_total: Pricing information containing the amount and the currency code. + :vartype purchases_total: ~azure.mgmt.reservations.models.Price + :ivar reservations_to_purchase: Details of the reservations being purchased. + :vartype reservations_to_purchase: + list[~azure.mgmt.reservations.models.ReservationToPurchaseCalculateExchange] + :ivar savings_plans_to_purchase: Details of the savings plans being purchased. + :vartype savings_plans_to_purchase: + list[~azure.mgmt.reservations.models.SavingsPlanToPurchaseCalculateExchange] + :ivar reservations_to_exchange: Details of the reservations being returned. + :vartype reservations_to_exchange: list[~azure.mgmt.reservations.models.ReservationToExchange] + :ivar policy_result: Exchange policy errors. + :vartype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors + """ + + session_id: Optional[str] = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """Exchange session identifier.""" + net_payable: Optional["_models.Price"] = rest_field( + name="netPayable", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + refunds_total: Optional["_models.Price"] = rest_field( + name="refundsTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + purchases_total: Optional["_models.Price"] = rest_field( + name="purchasesTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + reservations_to_purchase: Optional[list["_models.ReservationToPurchaseCalculateExchange"]] = rest_field( + name="reservationsToPurchase", visibility=["read", "create", "update", "delete", "query"] + ) + """Details of the reservations being purchased.""" + savings_plans_to_purchase: Optional[list["_models.SavingsPlanToPurchaseCalculateExchange"]] = rest_field( + name="savingsPlansToPurchase", visibility=["read", "create", "update", "delete", "query"] + ) + """Details of the savings plans being purchased.""" + reservations_to_exchange: Optional[list["_models.ReservationToExchange"]] = rest_field( + name="reservationsToExchange", visibility=["read", "create", "update", "delete", "query"] + ) + """Details of the reservations being returned.""" + policy_result: Optional["_models.ExchangePolicyErrors"] = rest_field( + name="policyResult", visibility=["read", "create", "update", "delete", "query"] + ) + """Exchange policy errors.""" + + @overload + def __init__( + self, + *, + session_id: Optional[str] = None, + net_payable: Optional["_models.Price"] = None, + refunds_total: Optional["_models.Price"] = None, + purchases_total: Optional["_models.Price"] = None, + reservations_to_purchase: Optional[list["_models.ReservationToPurchaseCalculateExchange"]] = None, + savings_plans_to_purchase: Optional[list["_models.SavingsPlanToPurchaseCalculateExchange"]] = None, + reservations_to_exchange: Optional[list["_models.ReservationToExchange"]] = None, + policy_result: Optional["_models.ExchangePolicyErrors"] = 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 CalculatePriceResponse(_Model): + """The response of calculate price for reservation. + + :ivar properties: Properties for calculate price response. + :vartype properties: ~azure.mgmt.reservations.models.CalculatePriceResponseProperties + """ + + properties: Optional["_models.CalculatePriceResponseProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for calculate price response.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.CalculatePriceResponseProperties"] = 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 CalculatePriceResponseProperties(_Model): + """Properties for calculate price response. + + :ivar billing_currency_total: Currency and amount that customer will be charged in customer's + local currency. Tax is not included. + :vartype billing_currency_total: + ~azure.mgmt.reservations.models.CalculatePriceResponsePropertiesBillingCurrencyTotal + :ivar net_total: Net total amount in pricing currency. + :vartype net_total: float + :ivar tax_total: Tax amount in pricing currency. + :vartype tax_total: float + :ivar grand_total: Total amount in pricing currency. + :vartype grand_total: float + :ivar is_tax_included: Whether or not tax is included in grand total. + :vartype is_tax_included: bool + :ivar is_billing_partner_managed: True if billing is managed by Microsoft Partner. Used only + for CSP accounts. + :vartype is_billing_partner_managed: bool + :ivar reservation_order_id: GUID that represents reservation order that can be placed after + calculating price. + :vartype reservation_order_id: str + :ivar sku_title: Title of sku that is being purchased. + :vartype sku_title: str + :ivar sku_description: Description of sku that is being purchased. + :vartype sku_description: str + :ivar pricing_currency_total: Amount that Microsoft uses for record. Used during refund for + calculating refund limit. Tax is not included. + :vartype pricing_currency_total: + ~azure.mgmt.reservations.models.CalculatePriceResponsePropertiesPricingCurrencyTotal + :ivar payment_schedule: + :vartype payment_schedule: list[~azure.mgmt.reservations.models.PaymentDetail] + """ + + billing_currency_total: Optional["_models.CalculatePriceResponsePropertiesBillingCurrencyTotal"] = rest_field( + name="billingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Currency and amount that customer will be charged in customer's local currency. Tax is not + included.""" + net_total: Optional[float] = rest_field(name="netTotal", visibility=["read", "create", "update", "delete", "query"]) + """Net total amount in pricing currency.""" + tax_total: Optional[float] = rest_field(name="taxTotal", visibility=["read", "create", "update", "delete", "query"]) + """Tax amount in pricing currency.""" + grand_total: Optional[float] = rest_field( + name="grandTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Total amount in pricing currency.""" + is_tax_included: Optional[bool] = rest_field( + name="isTaxIncluded", visibility=["read", "create", "update", "delete", "query"] + ) + """Whether or not tax is included in grand total.""" + is_billing_partner_managed: Optional[bool] = rest_field( + name="isBillingPartnerManaged", visibility=["read", "create", "update", "delete", "query"] + ) + """True if billing is managed by Microsoft Partner. Used only for CSP accounts.""" + reservation_order_id: Optional[str] = rest_field( + name="reservationOrderId", visibility=["read", "create", "update", "delete", "query"] + ) + """GUID that represents reservation order that can be placed after calculating price.""" + sku_title: Optional[str] = rest_field(name="skuTitle", visibility=["read", "create", "update", "delete", "query"]) + """Title of sku that is being purchased.""" + sku_description: Optional[str] = rest_field( + name="skuDescription", visibility=["read", "create", "update", "delete", "query"] + ) + """Description of sku that is being purchased.""" + pricing_currency_total: Optional["_models.CalculatePriceResponsePropertiesPricingCurrencyTotal"] = rest_field( + name="pricingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is + not included.""" + payment_schedule: Optional[list["_models.PaymentDetail"]] = rest_field( + name="paymentSchedule", visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + billing_currency_total: Optional["_models.CalculatePriceResponsePropertiesBillingCurrencyTotal"] = None, + net_total: Optional[float] = None, + tax_total: Optional[float] = None, + grand_total: Optional[float] = None, + is_tax_included: Optional[bool] = None, + is_billing_partner_managed: Optional[bool] = None, + reservation_order_id: Optional[str] = None, + sku_title: Optional[str] = None, + sku_description: Optional[str] = None, + pricing_currency_total: Optional["_models.CalculatePriceResponsePropertiesPricingCurrencyTotal"] = None, + payment_schedule: Optional[list["_models.PaymentDetail"]] = 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 CalculatePriceResponsePropertiesBillingCurrencyTotal(_Model): # pylint: disable=name-too-long + """Currency and amount that customer will be charged in customer's local currency. Tax is not + included. + + :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase + record. + :vartype currency_code: str + :ivar amount: Amount in pricing currency. Tax is not included. + :vartype amount: float + """ + + currency_code: Optional[str] = rest_field( + name="currencyCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The ISO 4217 3-letter currency code for the currency used by this purchase record.""" + amount: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Amount in pricing currency. Tax is not included.""" + + @overload + def __init__( + self, + *, + currency_code: Optional[str] = None, + amount: 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 CalculatePriceResponsePropertiesPricingCurrencyTotal(_Model): # pylint: disable=name-too-long + """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is + not included. + + :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase + record. + :vartype currency_code: str + :ivar amount: + :vartype amount: float + """ + + currency_code: Optional[str] = rest_field( + name="currencyCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The ISO 4217 3-letter currency code for the currency used by this purchase record.""" + amount: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + currency_code: Optional[str] = None, + amount: 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 CalculateRefundRequest(_Model): + """Request containing information needed for calculating refund. + + :ivar id: Fully qualified identifier of the reservation order being returned. + :vartype id: str + :ivar properties: Properties needed for calculate refund including the scope and the + reservation to be returned. + :vartype properties: ~azure.mgmt.reservations.models.CalculateRefundRequestProperties + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Fully qualified identifier of the reservation order being returned.""" + properties: Optional["_models.CalculateRefundRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties needed for calculate refund including the scope and the reservation to be returned.""" + + @overload + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + properties: Optional["_models.CalculateRefundRequestProperties"] = 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 CalculateRefundRequestProperties(_Model): + """Properties needed for calculate refund including the scope and the reservation to be returned. + + :ivar scope: The scope of the refund, e.g. Reservation. + :vartype scope: str + :ivar reservation_to_return: Reservation to return. + :vartype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn + """ + + scope: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The scope of the refund, e.g. Reservation.""" + reservation_to_return: Optional["_models.ReservationToReturn"] = rest_field( + name="reservationToReturn", visibility=["read", "create", "update", "delete", "query"] + ) + """Reservation to return.""" + + @overload + def __init__( + self, + *, + scope: Optional[str] = None, + reservation_to_return: Optional["_models.ReservationToReturn"] = 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 CalculateRefundResponse(_Model): + """The response of calculate refund containing refund information of reservation. + + :ivar id: Fully qualified identifier of the reservation being returned. + :vartype id: str + :ivar properties: The refund properties of reservation. + :vartype properties: ~azure.mgmt.reservations.models.RefundResponseProperties + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Fully qualified identifier of the reservation being returned.""" + properties: Optional["_models.RefundResponseProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The refund properties of reservation.""" + + @overload + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + properties: Optional["_models.RefundResponseProperties"] = 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 Catalog(_Model): + """Product details of a type of resource. + + :ivar resource_type: The type of resource the sku applies to. + :vartype resource_type: str + :ivar name: The name of sku. + :vartype name: str + :ivar billing_plans: The billing plan options available for this sku. + :vartype billing_plans: dict[str, list[str or + ~azure.mgmt.reservations.models.ReservationBillingPlan]] + :ivar terms: Available reservation terms for this resource. + :vartype terms: list[str or ~azure.mgmt.reservations.models.ReservationTerm] + :ivar locations: + :vartype locations: list[str] + :ivar sku_properties: + :vartype sku_properties: list[~azure.mgmt.reservations.models.SkuProperty] + :ivar msrp: Pricing information about the sku. + :vartype msrp: ~azure.mgmt.reservations.models.CatalogMsrp + :ivar restrictions: + :vartype restrictions: list[~azure.mgmt.reservations.models.SkuRestriction] + :ivar tier: The tier of this sku. + :vartype tier: str + :ivar size: The size of this sku. + :vartype size: str + :ivar capabilities: + :vartype capabilities: list[~azure.mgmt.reservations.models.SkuCapability] + """ + + resource_type: Optional[str] = rest_field(name="resourceType", visibility=["read"]) + """The type of resource the sku applies to.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of sku.""" + billing_plans: Optional[dict[str, list[Union[str, "_models.ReservationBillingPlan"]]]] = rest_field( + name="billingPlans", visibility=["read", "create", "update", "delete", "query"] + ) + """The billing plan options available for this sku.""" + terms: Optional[list[Union[str, "_models.ReservationTerm"]]] = rest_field(visibility=["read"]) + """Available reservation terms for this resource.""" + locations: Optional[list[str]] = rest_field(visibility=["read"]) + sku_properties: Optional[list["_models.SkuProperty"]] = rest_field(name="skuProperties", visibility=["read"]) + msrp: Optional["_models.CatalogMsrp"] = rest_field(visibility=["read"]) + """Pricing information about the sku.""" + restrictions: Optional[list["_models.SkuRestriction"]] = rest_field(visibility=["read"]) + tier: Optional[str] = rest_field(visibility=["read"]) + """The tier of this sku.""" + size: Optional[str] = rest_field(visibility=["read"]) + """The size of this sku.""" + capabilities: Optional[list["_models.SkuCapability"]] = rest_field(visibility=["read"]) + + @overload + def __init__( + self, + *, + billing_plans: Optional[dict[str, list[Union[str, "_models.ReservationBillingPlan"]]]] = 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 CatalogMsrp(_Model): + """Pricing information about the sku. + + :ivar p1_y: Amount in pricing currency. Tax not included. + :vartype p1_y: ~azure.mgmt.reservations.models.Price + :ivar p3_y: Amount in pricing currency. Tax not included. + :vartype p3_y: ~azure.mgmt.reservations.models.Price + :ivar p5_y: Amount in pricing currency. Tax not included. + :vartype p5_y: ~azure.mgmt.reservations.models.Price + """ + + p1_y: Optional["_models.Price"] = rest_field(name="p1Y", visibility=["read", "create", "update", "delete", "query"]) + """Amount in pricing currency. Tax not included.""" + p3_y: Optional["_models.Price"] = rest_field(name="p3Y", visibility=["read", "create", "update", "delete", "query"]) + """Amount in pricing currency. Tax not included.""" + p5_y: Optional["_models.Price"] = rest_field(name="p5Y", visibility=["read", "create", "update", "delete", "query"]) + """Amount in pricing currency. Tax not included.""" + + @overload + def __init__( + self, + *, + p1_y: Optional["_models.Price"] = None, + p3_y: Optional["_models.Price"] = None, + p5_y: Optional["_models.Price"] = 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 ChangeDirectoryRequest(_Model): + """Request body for change directory of a reservation. + + :ivar destination_tenant_id: Tenant id GUID that reservation order is to be transferred to. + :vartype destination_tenant_id: str + """ + + destination_tenant_id: Optional[str] = rest_field( + name="destinationTenantId", visibility=["read", "create", "update", "delete", "query"] + ) + """Tenant id GUID that reservation order is to be transferred to.""" + + @overload + def __init__( + self, + *, + destination_tenant_id: 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 ChangeDirectoryResponse(_Model): + """Change directory response. + + :ivar reservation_order: Change directory result for reservation order or reservation. + :vartype reservation_order: ~azure.mgmt.reservations.models.ChangeDirectoryResult + :ivar reservations: + :vartype reservations: list[~azure.mgmt.reservations.models.ChangeDirectoryResult] + """ + + reservation_order: Optional["_models.ChangeDirectoryResult"] = rest_field( + name="reservationOrder", visibility=["read", "create", "update", "delete", "query"] + ) + """Change directory result for reservation order or reservation.""" + reservations: Optional[list["_models.ChangeDirectoryResult"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + reservation_order: Optional["_models.ChangeDirectoryResult"] = None, + reservations: Optional[list["_models.ChangeDirectoryResult"]] = 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 ChangeDirectoryResult(_Model): + """Change directory result for reservation order or reservation. + + :ivar id: Identifier of the reservation order or reservation. + :vartype id: str + :ivar name: Name of the reservation order or reservation. + :vartype name: str + :ivar is_succeeded: True if change directory operation succeeded on this reservation order or + reservation. + :vartype is_succeeded: bool + :ivar error: Error reason if operation failed. Null otherwise. + :vartype error: str + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Identifier of the reservation order or reservation.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the reservation order or reservation.""" + is_succeeded: Optional[bool] = rest_field( + name="isSucceeded", visibility=["read", "create", "update", "delete", "query"] + ) + """True if change directory operation succeeded on this reservation order or reservation.""" + error: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error reason if operation failed. Null otherwise.""" + + @overload + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + is_succeeded: Optional[bool] = None, + error: 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 Price(_Model): + """Pricing information containing the amount and the currency code. + + :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase + record. + :vartype currency_code: str + :ivar amount: + :vartype amount: float + """ + + currency_code: Optional[str] = rest_field( + name="currencyCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The ISO 4217 3-letter currency code for the currency used by this purchase record.""" + amount: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + currency_code: Optional[str] = None, + amount: 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 Commitment(Price): + """Commitment towards the benefit. + + :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase + record. + :vartype currency_code: str + :ivar amount: + :vartype amount: float + :ivar grain: Commitment grain. "Hourly" + :vartype grain: str or ~azure.mgmt.reservations.models.CommitmentGrain + """ + + grain: Optional[Union[str, "_models.CommitmentGrain"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Commitment grain. \"Hourly\"""" + + @overload + def __init__( + self, + *, + currency_code: Optional[str] = None, + amount: Optional[float] = None, + grain: Optional[Union[str, "_models.CommitmentGrain"]] = 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 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.reservations.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 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.reservations.models.SystemData + """ + + +class CurrentQuotaLimitBase(ProxyResource): + """Quota properties. + + :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.reservations.models.SystemData + :ivar properties: Quota properties for the resource. + :vartype properties: ~azure.mgmt.reservations.models.QuotaProperties + """ + + properties: Optional["_models.QuotaProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Quota properties for the resource.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.QuotaProperties"] = 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 Error(_Model): + """Error information. + + :ivar error: Extended error information including error code and error message. + :vartype error: ~azure.mgmt.reservations.models.ExtendedErrorInfo + """ + + error: Optional["_models.ExtendedErrorInfo"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Extended error information including error code and error message.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ExtendedErrorInfo"] = 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 ErrorDetails(_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 + :ivar target: The target of the particular error. + :vartype target: str + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """Error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """Error message indicating why the operation failed.""" + target: Optional[str] = rest_field(visibility=["read"]) + """The target of the particular error.""" + + +class ErrorResponse(_Model): + """Error response indicates that the service is not able to process the incoming request. The + reason is provided in the error message. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.reservations.models.ErrorDetails + """ + + error: Optional["_models.ErrorDetails"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The details of the error.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ErrorDetails"] = 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 ExceptionResponse(_Model): + """The API error. + + :ivar error: The API error details. + :vartype error: ~azure.mgmt.reservations.models.ServiceError + """ + + error: Optional["_models.ServiceError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The API error details.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ServiceError"] = 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 ExchangeOperationResultResponse(_Model): + """Exchange operation result. + + :ivar id: It should match what is used to GET the operation result. + :vartype id: str + :ivar name: It must match the last segment of the id field, and will typically be a GUID / + system generated value. + :vartype name: str + :ivar status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", + "PendingRefunds", and "PendingPurchases". + :vartype status: str or ~azure.mgmt.reservations.models.ExchangeOperationResultStatus + :ivar properties: Exchange response properties. + :vartype properties: ~azure.mgmt.reservations.models.ExchangeResponseProperties + :ivar error: Required if status == failed or status == canceled. + :vartype error: ~azure.mgmt.reservations.models.OperationResultError + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """It should match what is used to GET the operation result.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """It must match the last segment of the id field, and will typically be a GUID / system generated + value.""" + status: Optional[Union[str, "_models.ExchangeOperationResultStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Status of the operation. Known values are: \"Succeeded\", \"Failed\", \"Cancelled\", + \"PendingRefunds\", and \"PendingPurchases\".""" + properties: Optional["_models.ExchangeResponseProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Exchange response properties.""" + error: Optional["_models.OperationResultError"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Required if status == failed or status == canceled.""" + + @overload + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + status: Optional[Union[str, "_models.ExchangeOperationResultStatus"]] = None, + properties: Optional["_models.ExchangeResponseProperties"] = None, + error: Optional["_models.OperationResultError"] = 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 ExchangePolicyError(_Model): + """error details. + + :ivar code: + :vartype code: str + :ivar message: + :vartype message: str + """ + + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + message: 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 ExchangePolicyErrors(_Model): + """Exchange policy errors. + + :ivar policy_errors: Exchange Policy errors. + :vartype policy_errors: list[~azure.mgmt.reservations.models.ExchangePolicyError] + """ + + policy_errors: Optional[list["_models.ExchangePolicyError"]] = rest_field( + name="policyErrors", visibility=["read", "create", "update", "delete", "query"] + ) + """Exchange Policy errors.""" + + @overload + def __init__( + self, + *, + policy_errors: Optional[list["_models.ExchangePolicyError"]] = 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 ExchangeRequest(_Model): + """Exchange request. + + :ivar properties: Exchange request properties. + :vartype properties: ~azure.mgmt.reservations.models.ExchangeRequestProperties + """ + + properties: Optional["_models.ExchangeRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Exchange request properties.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.ExchangeRequestProperties"] = 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 ExchangeRequestProperties(_Model): + """Exchange request properties. + + :ivar session_id: SessionId that was returned by CalculateExchange API. + :vartype session_id: str + """ + + session_id: Optional[str] = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """SessionId that was returned by CalculateExchange API.""" + + @overload + def __init__( + self, + *, + session_id: 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 ExchangeResponseProperties(_Model): + """Exchange response properties. + + :ivar session_id: Exchange session identifier. + :vartype session_id: str + :ivar net_payable: Pricing information containing the amount and the currency code. + :vartype net_payable: ~azure.mgmt.reservations.models.Price + :ivar refunds_total: Pricing information containing the amount and the currency code. + :vartype refunds_total: ~azure.mgmt.reservations.models.Price + :ivar purchases_total: Pricing information containing the amount and the currency code. + :vartype purchases_total: ~azure.mgmt.reservations.models.Price + :ivar reservations_to_purchase: Details of the reservations being purchased. + :vartype reservations_to_purchase: + list[~azure.mgmt.reservations.models.ReservationToPurchaseExchange] + :ivar savings_plans_to_purchase: Details of the savings plans being purchased. + :vartype savings_plans_to_purchase: + list[~azure.mgmt.reservations.models.SavingsPlanToPurchaseExchange] + :ivar reservations_to_exchange: Details of the reservations being returned. + :vartype reservations_to_exchange: + list[~azure.mgmt.reservations.models.ReservationToReturnForExchange] + :ivar policy_result: Exchange policy errors. + :vartype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors + """ + + session_id: Optional[str] = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """Exchange session identifier.""" + net_payable: Optional["_models.Price"] = rest_field( + name="netPayable", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + refunds_total: Optional["_models.Price"] = rest_field( + name="refundsTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + purchases_total: Optional["_models.Price"] = rest_field( + name="purchasesTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + reservations_to_purchase: Optional[list["_models.ReservationToPurchaseExchange"]] = rest_field( + name="reservationsToPurchase", visibility=["read", "create", "update", "delete", "query"] + ) + """Details of the reservations being purchased.""" + savings_plans_to_purchase: Optional[list["_models.SavingsPlanToPurchaseExchange"]] = rest_field( + name="savingsPlansToPurchase", visibility=["read", "create", "update", "delete", "query"] + ) + """Details of the savings plans being purchased.""" + reservations_to_exchange: Optional[list["_models.ReservationToReturnForExchange"]] = rest_field( + name="reservationsToExchange", visibility=["read", "create", "update", "delete", "query"] + ) + """Details of the reservations being returned.""" + policy_result: Optional["_models.ExchangePolicyErrors"] = rest_field( + name="policyResult", visibility=["read", "create", "update", "delete", "query"] + ) + """Exchange policy errors.""" + + @overload + def __init__( + self, + *, + session_id: Optional[str] = None, + net_payable: Optional["_models.Price"] = None, + refunds_total: Optional["_models.Price"] = None, + purchases_total: Optional["_models.Price"] = None, + reservations_to_purchase: Optional[list["_models.ReservationToPurchaseExchange"]] = None, + savings_plans_to_purchase: Optional[list["_models.SavingsPlanToPurchaseExchange"]] = None, + reservations_to_exchange: Optional[list["_models.ReservationToReturnForExchange"]] = None, + policy_result: Optional["_models.ExchangePolicyErrors"] = 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 ExtendedErrorInfo(_Model): + """Extended error information including error code and error message. + + :ivar code: Error code describing the reason that service is not able to process the incoming + request. Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", + "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", + "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", + "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", + "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", + "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", + "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", + "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", + "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", + "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", + "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", + "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", + "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", + "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", + "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", + "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", + "BillingTransientError", "BillingError", "FulfillmentConfigurationError", + "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", + "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and + "RefundLimitExceeded". + :vartype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode + :ivar message: + :vartype message: str + """ + + code: Optional[Union[str, "_models.ErrorResponseCode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Error code describing the reason that service is not able to process the incoming request. + Known values are: \"NotSpecified\", \"InternalServerError\", \"ServerTimeout\", + \"AuthorizationFailed\", \"BadRequest\", \"ClientCertificateThumbprintNotSet\", + \"InvalidRequestContent\", \"OperationFailed\", \"HttpMethodNotSupported\", + \"InvalidRequestUri\", \"MissingTenantId\", \"InvalidTenantId\", \"InvalidReservationOrderId\", + \"InvalidReservationId\", \"ReservationIdNotInReservationOrder\", \"ReservationOrderNotFound\", + \"InvalidSubscriptionId\", \"InvalidAccessToken\", \"InvalidLocationId\", + \"UnauthenticatedRequestsThrottled\", \"InvalidHealthCheckType\", \"Forbidden\", + \"BillingScopeIdCannotBeChanged\", \"AppliedScopesNotAssociatedWithCommerceAccount\", + \"PatchValuesSameAsExisting\", \"RoleAssignmentCreationFailed\", + \"ReservationOrderCreationFailed\", \"ReservationOrderNotEnabled\", + \"CapacityUpdateScopesFailed\", \"UnsupportedReservationTerm\", + \"ReservationOrderIdAlreadyExists\", \"RiskCheckFailed\", \"CreateQuoteFailed\", + \"ActivateQuoteFailed\", \"NonsupportedAccountId\", \"PaymentInstrumentNotFound\", + \"MissingAppliedScopesForSingle\", \"NoValidReservationsToReRate\", \"ReRateOnlyAllowedForEA\", + \"OperationCannotBePerformedInCurrentState\", \"InvalidSingleAppliedScopesCount\", + \"InvalidFulfillmentRequestParameters\", \"NotSupportedCountry\", \"InvalidRefundQuantity\", + \"PurchaseError\", \"BillingCustomerInputError\", \"BillingPaymentInstrumentSoftError\", + \"BillingPaymentInstrumentHardError\", \"BillingTransientError\", \"BillingError\", + \"FulfillmentConfigurationError\", \"FulfillmentOutOfStockError\", + \"FulfillmentTransientError\", \"FulfillmentError\", \"CalculatePriceFailed\", + \"AppliedScopesSameAsExisting\", \"SelfServiceRefundNotSupported\", and + \"RefundLimitExceeded\".""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + code: Optional[Union[str, "_models.ErrorResponseCode"]] = None, + message: 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 ExtendedStatusInfo(_Model): + """ExtendedStatusInfo. + + :ivar status_code: Known values are: "None", "Pending", "Processing", "Active", + "PurchaseError", "PaymentInstrumentError", "Split", "Merged", "Expired", and "Succeeded". + :vartype status_code: str or ~azure.mgmt.reservations.models.ReservationStatusCode + :ivar message: The message giving detailed information about the status code. + :vartype message: str + """ + + status_code: Optional[Union[str, "_models.ReservationStatusCode"]] = rest_field( + name="statusCode", visibility=["read", "create", "update", "delete", "query"] + ) + """Known values are: \"None\", \"Pending\", \"Processing\", \"Active\", \"PurchaseError\", + \"PaymentInstrumentError\", \"Split\", \"Merged\", \"Expired\", and \"Succeeded\".""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The message giving detailed information about the status code.""" + + @overload + def __init__( + self, + *, + status_code: Optional[Union[str, "_models.ReservationStatusCode"]] = None, + message: 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 MergeProperties(_Model): + """Properties for reservation merge. + + :ivar sources: Format of the resource id should be + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype sources: list[str] + """ + + sources: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Format of the resource id should be + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + + @overload + def __init__( + self, + *, + sources: 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 MergeRequest(_Model): + """The request for reservation merge. + + :ivar properties: Properties for reservation merge. + :vartype properties: ~azure.mgmt.reservations.models.MergeProperties + """ + + properties: Optional["_models.MergeProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for reservation merge.""" + + __flattened_items = ["sources"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.MergeProperties"] = 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 OperationDisplay(_Model): + """Information about an operation. + + :ivar provider: + :vartype provider: str + :ivar resource: + :vartype resource: str + :ivar operation: + :vartype operation: str + :ivar description: + :vartype description: str + """ + + provider: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + resource: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + operation: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: 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 OperationResponse(_Model): + """The response containing operation information. + + :ivar name: Name of the operation. + :vartype name: str + :ivar is_data_action: Indicates whether the operation is a data action. + :vartype is_data_action: bool + :ivar display: Display of the operation. + :vartype display: ~azure.mgmt.reservations.models.OperationDisplay + :ivar origin: Origin of the operation. + :vartype origin: str + :ivar properties: Properties of the operation. + :vartype properties: any + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the operation.""" + is_data_action: Optional[bool] = rest_field( + name="isDataAction", visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether the operation is a data action.""" + display: Optional["_models.OperationDisplay"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Display of the operation.""" + origin: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Origin of the operation.""" + properties: Optional[Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Properties of the operation.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + is_data_action: Optional[bool] = None, + display: Optional["_models.OperationDisplay"] = None, + origin: Optional[str] = None, + properties: Optional[Any] = 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 OperationResultError(_Model): + """Required if status == failed or status == canceled. + + :ivar code: Required if status == failed or status == cancelled. If status == failed, provide + an invariant error code used for error troubleshooting, aggregation, and analysis. + :vartype code: str + :ivar message: Required if status == failed. Localized. If status == failed, provide an + actionable error message indicating what error occurred, and what the user can do to address + the issue. + :vartype message: str + """ + + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required if status == failed or status == cancelled. If status == failed, provide an invariant + error code used for error troubleshooting, aggregation, and analysis.""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required if status == failed. Localized. If status == failed, provide an actionable error + message indicating what error occurred, and what the user can do to address the issue.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + message: 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 Patch(_Model): + """The request for reservation patch. + + :ivar properties: Properties for reservation patch. + :vartype properties: ~azure.mgmt.reservations.models.PatchProperties + """ + + properties: Optional["_models.PatchProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for reservation patch.""" + + __flattened_items = [ + "applied_scope_type", + "applied_scopes", + "applied_scope_properties", + "instance_flexibility", + "name", + "renew", + "renew_properties", + "review_date_time", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.PatchProperties"] = 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 PatchProperties(_Model): + """Properties for reservation patch. + + :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and + "ManagementGroup". + :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType + :ivar applied_scopes: List of the subscriptions that the benefit will be applied. Do not + specify if AppliedScopeType is Shared. This property will be deprecated and replaced by + appliedScopeProperties instead for Single AppliedScopeType. + :vartype applied_scopes: list[str] + :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not + applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is + ManagementGroup. + :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties + :ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in + the same VM size group. Only specify for VirtualMachines reserved resource type. Known values + are: "On" and "Off". + :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility + :ivar name: Display name of the reservation. + :vartype name: str + :ivar renew: Setting this to true will automatically purchase a new reservation on the + expiration date time. + :vartype renew: bool + :ivar renew_properties: + :vartype renew_properties: ~azure.mgmt.reservations.models.PatchPropertiesRenewProperties + :ivar review_date_time: This is the date-time when the Azure hybrid benefit needs to be + reviewed. + :vartype review_date_time: ~datetime.datetime + """ + + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = rest_field( + name="appliedScopeType", visibility=["read", "create", "update", "delete", "query"] + ) + """Type of the Applied Scope. Known values are: \"Single\", \"Shared\", and \"ManagementGroup\".""" + applied_scopes: Optional[list[str]] = rest_field( + name="appliedScopes", visibility=["read", "create", "update", "delete", "query"] + ) + """List of the subscriptions that the benefit will be applied. Do not specify if AppliedScopeType + is Shared. This property will be deprecated and replaced by appliedScopeProperties instead for + Single AppliedScopeType.""" + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = rest_field( + name="appliedScopeProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties specific to applied scope type. Not required if not applicable. Required and need to + provide tenantId and managementGroupId if AppliedScopeType is ManagementGroup.""" + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = rest_field( + name="instanceFlexibility", visibility=["read", "create", "update", "delete", "query"] + ) + """Turning this on will apply the reservation discount to other VMs in the same VM size group. + Only specify for VirtualMachines reserved resource type. Known values are: \"On\" and \"Off\".""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name of the reservation.""" + renew: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Setting this to true will automatically purchase a new reservation on the expiration date time.""" + renew_properties: Optional["_models.PatchPropertiesRenewProperties"] = rest_field( + name="renewProperties", visibility=["read", "create", "update", "delete", "query"] + ) + review_date_time: Optional[datetime.datetime] = rest_field( + name="reviewDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the date-time when the Azure hybrid benefit needs to be reviewed.""" + + @overload + def __init__( + self, + *, + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, + applied_scopes: Optional[list[str]] = None, + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, + name: Optional[str] = None, + renew: Optional[bool] = None, + renew_properties: Optional["_models.PatchPropertiesRenewProperties"] = None, + review_date_time: 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 PatchPropertiesRenewProperties(_Model): + """PatchPropertiesRenewProperties. + + :ivar purchase_properties: The request for reservation purchase. + :vartype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest + """ + + purchase_properties: Optional["_models.PurchaseRequest"] = rest_field( + name="purchaseProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """The request for reservation purchase.""" + + @overload + def __init__( + self, + *, + purchase_properties: Optional["_models.PurchaseRequest"] = 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 PaymentDetail(_Model): + """Information about payment related to a reservation order. + + :ivar due_date: Date when the payment needs to be done. + :vartype due_date: ~datetime.date + :ivar payment_date: Date when the transaction is completed. Is null when it is scheduled. + :vartype payment_date: ~datetime.date + :ivar pricing_currency_total: Amount in pricing currency. Tax not included. + :vartype pricing_currency_total: ~azure.mgmt.reservations.models.Price + :ivar billing_currency_total: Amount charged in Billing currency. Tax not included. Is null for + future payments. + :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price + :ivar billing_account: Shows the Account that is charged for this payment. + :vartype billing_account: str + :ivar status: Describes whether the payment is completed, failed, cancelled or scheduled in the + future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled". + :vartype status: str or ~azure.mgmt.reservations.models.PaymentStatus + :ivar extended_status_info: + :vartype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo + """ + + due_date: Optional[datetime.date] = rest_field( + name="dueDate", visibility=["read", "create", "update", "delete", "query"] + ) + """Date when the payment needs to be done.""" + payment_date: Optional[datetime.date] = rest_field( + name="paymentDate", visibility=["read", "create", "update", "delete", "query"] + ) + """Date when the transaction is completed. Is null when it is scheduled.""" + pricing_currency_total: Optional["_models.Price"] = rest_field( + name="pricingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Amount in pricing currency. Tax not included.""" + billing_currency_total: Optional["_models.Price"] = rest_field( + name="billingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Amount charged in Billing currency. Tax not included. Is null for future payments.""" + billing_account: Optional[str] = rest_field( + name="billingAccount", visibility=["read", "create", "update", "delete", "query"] + ) + """Shows the Account that is charged for this payment.""" + status: Optional[Union[str, "_models.PaymentStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Describes whether the payment is completed, failed, cancelled or scheduled in the future. Known + values are: \"Succeeded\", \"Failed\", \"Scheduled\", and \"Cancelled\".""" + extended_status_info: Optional["_models.ExtendedStatusInfo"] = rest_field( + name="extendedStatusInfo", visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + due_date: Optional[datetime.date] = None, + payment_date: Optional[datetime.date] = None, + pricing_currency_total: Optional["_models.Price"] = None, + billing_currency_total: Optional["_models.Price"] = None, + billing_account: Optional[str] = None, + status: Optional[Union[str, "_models.PaymentStatus"]] = None, + extended_status_info: Optional["_models.ExtendedStatusInfo"] = 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 PurchaseRequest(_Model): + """The request for reservation purchase. + + :ivar sku: The name of sku. + :vartype sku: ~azure.mgmt.reservations.models.SkuName + :ivar location: The Azure region where the reserved resource lives. + :vartype location: str + :ivar properties: Properties of reservation purchase request. + :vartype properties: ~azure.mgmt.reservations.models.PurchaseRequestProperties + """ + + sku: Optional["_models.SkuName"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of sku.""" + location: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """The Azure region where the reserved resource lives.""" + properties: Optional["_models.PurchaseRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of reservation purchase request.""" + + __flattened_items = [ + "reserved_resource_type", + "billing_scope_id", + "term", + "billing_plan", + "quantity", + "display_name", + "applied_scope_type", + "applied_scopes", + "applied_scope_properties", + "renew", + "reserved_resource_properties", + "review_date_time", + ] + + @overload + def __init__( + self, + *, + sku: Optional["_models.SkuName"] = None, + location: Optional[str] = None, + properties: Optional["_models.PurchaseRequestProperties"] = 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 PurchaseRequestProperties(_Model): + """Properties of reservation purchase request. + + :ivar reserved_resource_type: The type of the resource that is being reserved. In addition to + below types we have also added the following: OpenAIPTU, MDC, Sentinel. Known values are: + "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", + "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", + "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", + "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", + "SqlEdge", and "VirtualMachineSoftware". + :vartype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType + :ivar billing_scope_id: Subscription that will be charged for purchasing reservation or savings + plan. + :vartype billing_scope_id: str + :ivar term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". + :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm + :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". + :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan + :ivar quantity: Quantity of the skus that are part of the reservation. + :vartype quantity: int + :ivar display_name: Friendly name of the reservation. + :vartype display_name: str + :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and + "ManagementGroup". + :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType + :ivar applied_scopes: List of the subscriptions that the benefit will be applied. Do not + specify if AppliedScopeType is Shared. This property will be deprecated and replaced by + appliedScopeProperties instead for Single AppliedScopeType. + :vartype applied_scopes: list[str] + :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not + applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is + ManagementGroup. + :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties + :ivar renew: Setting this to true will automatically purchase a new reservation on the + expiration date time. + :vartype renew: bool + :ivar reserved_resource_properties: Properties specific to each reserved resource type. Not + required if not applicable. + :vartype reserved_resource_properties: + ~azure.mgmt.reservations.models.PurchaseRequestPropertiesReservedResourceProperties + :ivar review_date_time: This is the date-time when the Azure hybrid benefit needs to be + reviewed. + :vartype review_date_time: ~datetime.datetime + """ + + reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = rest_field( + name="reservedResourceType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of the resource that is being reserved. In addition to below types we have also added + the following: OpenAIPTU, MDC, Sentinel. Known values are: \"VirtualMachines\", + \"SqlDatabases\", \"SuseLinux\", \"CosmosDb\", \"RedHat\", \"SqlDataWarehouse\", + \"VMwareCloudSimple\", \"RedHatOsa\", \"Databricks\", \"AppService\", \"ManagedDisk\", + \"BlockBlob\", \"RedisCache\", \"AzureDataExplorer\", \"MySql\", \"MariaDb\", \"PostgreSql\", + \"DedicatedHost\", \"SapHana\", \"SqlAzureHybridBenefit\", \"AVS\", \"DataFactory\", + \"NetAppStorage\", \"AzureFiles\", \"SqlEdge\", and \"VirtualMachineSoftware\".""" + billing_scope_id: Optional[str] = rest_field( + name="billingScopeId", visibility=["read", "create", "update", "delete", "query"] + ) + """Subscription that will be charged for purchasing reservation or savings plan.""" + term: Optional[Union[str, "_models.ReservationTerm"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Represent the term of reservation. Known values are: \"P1Y\", \"P3Y\", and \"P5Y\".""" + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = rest_field( + name="billingPlan", visibility=["read", "create", "update", "delete", "query"] + ) + """Represent the billing plans. Known values are: \"Upfront\" and \"Monthly\".""" + quantity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quantity of the skus that are part of the reservation.""" + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """Friendly name of the reservation.""" + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = rest_field( + name="appliedScopeType", visibility=["read", "create", "update", "delete", "query"] + ) + """Type of the Applied Scope. Known values are: \"Single\", \"Shared\", and \"ManagementGroup\".""" + applied_scopes: Optional[list[str]] = rest_field( + name="appliedScopes", visibility=["read", "create", "update", "delete", "query"] + ) + """List of the subscriptions that the benefit will be applied. Do not specify if AppliedScopeType + is Shared. This property will be deprecated and replaced by appliedScopeProperties instead for + Single AppliedScopeType.""" + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = rest_field( + name="appliedScopeProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties specific to applied scope type. Not required if not applicable. Required and need to + provide tenantId and managementGroupId if AppliedScopeType is ManagementGroup.""" + renew: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Setting this to true will automatically purchase a new reservation on the expiration date time.""" + reserved_resource_properties: Optional["_models.PurchaseRequestPropertiesReservedResourceProperties"] = rest_field( + name="reservedResourceProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties specific to each reserved resource type. Not required if not applicable.""" + review_date_time: Optional[datetime.datetime] = rest_field( + name="reviewDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the date-time when the Azure hybrid benefit needs to be reviewed.""" + + @overload + def __init__( + self, + *, + reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None, + billing_scope_id: Optional[str] = None, + term: Optional[Union[str, "_models.ReservationTerm"]] = None, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, + quantity: Optional[int] = None, + display_name: Optional[str] = None, + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, + applied_scopes: Optional[list[str]] = None, + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, + renew: Optional[bool] = None, + reserved_resource_properties: Optional["_models.PurchaseRequestPropertiesReservedResourceProperties"] = None, + review_date_time: 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 PurchaseRequestPropertiesReservedResourceProperties(_Model): # pylint: disable=name-too-long + """Properties specific to each reserved resource type. Not required if not applicable. + + :ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in + the same VM size group. Only specify for VirtualMachines reserved resource type. Known values + are: "On" and "Off". + :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility + """ + + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = rest_field( + name="instanceFlexibility", visibility=["read", "create", "update", "delete", "query"] + ) + """Turning this on will apply the reservation discount to other VMs in the same VM size group. + Only specify for VirtualMachines reserved resource type. Known values are: \"On\" and \"Off\".""" + + @overload + def __init__( + self, + *, + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = 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 QuotaProperties(_Model): + """Quota properties for the resource. + + :ivar limit: Quota properties. + :vartype limit: int + :ivar current_value: Current usage value for the resource. + :vartype current_value: int + :ivar unit: The limit units, such as **count** and **bytes**. Use the unit field provided in + the response of the GET quota operation. + :vartype unit: str + :ivar name: Name of the resource provide by the resource provider. Use this property for + quotaRequests resource operations. + :vartype name: ~azure.mgmt.reservations.models.ResourceName + :ivar resource_type: The name of the resource type. Known values are: "standard", "dedicated", + "lowPriority", "shared", and "serviceSpecific". + :vartype resource_type: str or ~azure.mgmt.reservations.models.ResourceType + :ivar quota_period: The time period over which the quota usage values are summarized. For + example, P1D (per one day), PT1M (per one minute), and PT1S (per one second). This parameter is + optional because, for some resources such as compute, the time period is irrelevant. + :vartype quota_period: str + :ivar properties: Additional properties for the specified resource provider. + :vartype properties: any + """ + + limit: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quota properties.""" + current_value: Optional[int] = rest_field(name="currentValue", visibility=["read"]) + """Current usage value for the resource.""" + unit: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The limit units, such as **count** and **bytes**. Use the unit field provided in the response + of the GET quota operation.""" + name: Optional["_models.ResourceName"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the resource provide by the resource provider. Use this property for quotaRequests + resource operations.""" + resource_type: Optional[Union[str, "_models.ResourceType"]] = rest_field( + name="resourceType", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the resource type. Known values are: \"standard\", \"dedicated\", \"lowPriority\", + \"shared\", and \"serviceSpecific\".""" + quota_period: Optional[str] = rest_field(name="quotaPeriod", visibility=["read"]) + """The time period over which the quota usage values are summarized. For example, P1D (per one + day), PT1M (per one minute), and PT1S (per one second). This parameter is optional because, for + some resources such as compute, the time period is irrelevant.""" + properties: Optional[Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional properties for the specified resource provider.""" + + @overload + def __init__( + self, + *, + limit: Optional[int] = None, + unit: Optional[str] = None, + name: Optional["_models.ResourceName"] = None, + resource_type: Optional[Union[str, "_models.ResourceType"]] = None, + properties: Optional[Any] = 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 QuotaRequestDetails(ProxyResource): + """Quota request 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.reservations.models.SystemData + :ivar properties: Quota request details. + :vartype properties: ~azure.mgmt.reservations.models.QuotaRequestProperties + """ + + properties: Optional["_models.QuotaRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Quota request details.""" + + __flattened_items = ["provisioning_state", "message", "request_submit_time", "value"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.QuotaRequestProperties"] = 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 QuotaRequestProperties(_Model): + """The details of quota request. + + :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". + :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState + :ivar message: User friendly status message. + :vartype message: str + :ivar request_submit_time: The time when the quota request was submitted using format: + yyyy-MM-ddTHH:mm:ssZ as specified by the ISO 8601 standard. + :vartype request_submit_time: ~datetime.datetime + :ivar value: The quotaRequests. + :vartype value: list[~azure.mgmt.reservations.models.SubRequest] + """ + + provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = rest_field( + name="provisioningState", visibility=["read", "create", "update", "delete", "query"] + ) + """The quota request status. Known values are: \"Accepted\", \"Invalid\", \"Succeeded\", + \"Failed\", and \"InProgress\".""" + message: Optional[str] = rest_field(visibility=["read"]) + """User friendly status message.""" + request_submit_time: Optional[datetime.datetime] = rest_field( + name="requestSubmitTime", visibility=["read"], format="rfc3339" + ) + """The time when the quota request was submitted using format: yyyy-MM-ddTHH:mm:ssZ as specified + by the ISO 8601 standard.""" + value: Optional[list["_models.SubRequest"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The quotaRequests.""" + + @overload + def __init__( + self, + *, + provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = None, + value: Optional[list["_models.SubRequest"]] = 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 RefundBillingInformation(_Model): + """billing information. + + :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". + :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan + :ivar completed_transactions: The number of completed transactions in this reservation's + payment. + :vartype completed_transactions: int + :ivar total_transactions: The number of total transactions in this reservation's payment. + :vartype total_transactions: int + :ivar billing_currency_total_paid_amount: Pricing information containing the amount and the + currency code. + :vartype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_currency_prorated_amount: Pricing information containing the amount and the + currency code. + :vartype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_currency_remaining_commitment_amount: Pricing information containing the amount + and the currency code. + :vartype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price + """ + + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = rest_field( + name="billingPlan", visibility=["read", "create", "update", "delete", "query"] + ) + """Represent the billing plans. Known values are: \"Upfront\" and \"Monthly\".""" + completed_transactions: Optional[int] = rest_field( + name="completedTransactions", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of completed transactions in this reservation's payment.""" + total_transactions: Optional[int] = rest_field( + name="totalTransactions", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of total transactions in this reservation's payment.""" + billing_currency_total_paid_amount: Optional["_models.Price"] = rest_field( + name="billingCurrencyTotalPaidAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + billing_currency_prorated_amount: Optional["_models.Price"] = rest_field( + name="billingCurrencyProratedAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + billing_currency_remaining_commitment_amount: Optional["_models.Price"] = rest_field( + name="billingCurrencyRemainingCommitmentAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + + @overload + def __init__( + self, + *, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, + completed_transactions: Optional[int] = None, + total_transactions: Optional[int] = None, + billing_currency_total_paid_amount: Optional["_models.Price"] = None, + billing_currency_prorated_amount: Optional["_models.Price"] = None, + billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None, + ) -> 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 RefundPolicyError(_Model): + """error details. + + :ivar code: Error code describing the reason that service is not able to process the incoming + request. Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", + "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", + "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", + "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", + "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", + "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", + "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", + "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", + "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", + "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", + "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", + "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", + "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", + "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", + "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", + "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", + "BillingTransientError", "BillingError", "FulfillmentConfigurationError", + "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", + "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and + "RefundLimitExceeded". + :vartype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode + :ivar message: + :vartype message: str + """ + + code: Optional[Union[str, "_models.ErrorResponseCode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Error code describing the reason that service is not able to process the incoming request. + Known values are: \"NotSpecified\", \"InternalServerError\", \"ServerTimeout\", + \"AuthorizationFailed\", \"BadRequest\", \"ClientCertificateThumbprintNotSet\", + \"InvalidRequestContent\", \"OperationFailed\", \"HttpMethodNotSupported\", + \"InvalidRequestUri\", \"MissingTenantId\", \"InvalidTenantId\", \"InvalidReservationOrderId\", + \"InvalidReservationId\", \"ReservationIdNotInReservationOrder\", \"ReservationOrderNotFound\", + \"InvalidSubscriptionId\", \"InvalidAccessToken\", \"InvalidLocationId\", + \"UnauthenticatedRequestsThrottled\", \"InvalidHealthCheckType\", \"Forbidden\", + \"BillingScopeIdCannotBeChanged\", \"AppliedScopesNotAssociatedWithCommerceAccount\", + \"PatchValuesSameAsExisting\", \"RoleAssignmentCreationFailed\", + \"ReservationOrderCreationFailed\", \"ReservationOrderNotEnabled\", + \"CapacityUpdateScopesFailed\", \"UnsupportedReservationTerm\", + \"ReservationOrderIdAlreadyExists\", \"RiskCheckFailed\", \"CreateQuoteFailed\", + \"ActivateQuoteFailed\", \"NonsupportedAccountId\", \"PaymentInstrumentNotFound\", + \"MissingAppliedScopesForSingle\", \"NoValidReservationsToReRate\", \"ReRateOnlyAllowedForEA\", + \"OperationCannotBePerformedInCurrentState\", \"InvalidSingleAppliedScopesCount\", + \"InvalidFulfillmentRequestParameters\", \"NotSupportedCountry\", \"InvalidRefundQuantity\", + \"PurchaseError\", \"BillingCustomerInputError\", \"BillingPaymentInstrumentSoftError\", + \"BillingPaymentInstrumentHardError\", \"BillingTransientError\", \"BillingError\", + \"FulfillmentConfigurationError\", \"FulfillmentOutOfStockError\", + \"FulfillmentTransientError\", \"FulfillmentError\", \"CalculatePriceFailed\", + \"AppliedScopesSameAsExisting\", \"SelfServiceRefundNotSupported\", and + \"RefundLimitExceeded\".""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + code: Optional[Union[str, "_models.ErrorResponseCode"]] = None, + message: 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 RefundPolicyResult(_Model): + """Refund policy result. + + :ivar properties: Refund policy result property. + :vartype properties: ~azure.mgmt.reservations.models.RefundPolicyResultProperty + """ + + properties: Optional["_models.RefundPolicyResultProperty"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Refund policy result property.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.RefundPolicyResultProperty"] = 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 RefundPolicyResultProperty(_Model): + """Refund policy result property. + + :ivar consumed_refunds_total: Pricing information containing the amount and the currency code. + :vartype consumed_refunds_total: ~azure.mgmt.reservations.models.Price + :ivar max_refund_limit: Pricing information containing the amount and the currency code. + :vartype max_refund_limit: ~azure.mgmt.reservations.models.Price + :ivar policy_errors: Refund Policy errors. + :vartype policy_errors: list[~azure.mgmt.reservations.models.RefundPolicyError] + """ + + consumed_refunds_total: Optional["_models.Price"] = rest_field( + name="consumedRefundsTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + max_refund_limit: Optional["_models.Price"] = rest_field( + name="maxRefundLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + policy_errors: Optional[list["_models.RefundPolicyError"]] = rest_field( + name="policyErrors", visibility=["read", "create", "update", "delete", "query"] + ) + """Refund Policy errors.""" + + @overload + def __init__( + self, + *, + consumed_refunds_total: Optional["_models.Price"] = None, + max_refund_limit: Optional["_models.Price"] = None, + policy_errors: Optional[list["_models.RefundPolicyError"]] = 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 RefundRequest(_Model): + """Request containing information needed for returning reservation. + + :ivar properties: Properties needed for refund request including the session id from calculate + refund, the scope, the reservation to be returned and the return reason. + :vartype properties: ~azure.mgmt.reservations.models.RefundRequestProperties + """ + + properties: Optional["_models.RefundRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties needed for refund request including the session id from calculate refund, the scope, + the reservation to be returned and the return reason.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.RefundRequestProperties"] = 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 RefundRequestProperties(_Model): + """Properties needed for refund request including the session id from calculate refund, the scope, + the reservation to be returned and the return reason. + + :ivar session_id: SessionId that was returned by CalculateRefund API. + :vartype session_id: str + :ivar scope: The scope of the refund, e.g. Reservation. + :vartype scope: str + :ivar reservation_to_return: Reservation to return. + :vartype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn + :ivar return_reason: The reason of returning the reservation. + :vartype return_reason: str + """ + + session_id: Optional[str] = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """SessionId that was returned by CalculateRefund API.""" + scope: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The scope of the refund, e.g. Reservation.""" + reservation_to_return: Optional["_models.ReservationToReturn"] = rest_field( + name="reservationToReturn", visibility=["read", "create", "update", "delete", "query"] + ) + """Reservation to return.""" + return_reason: Optional[str] = rest_field( + name="returnReason", visibility=["read", "create", "update", "delete", "query"] + ) + """The reason of returning the reservation.""" + + @overload + def __init__( + self, + *, + session_id: Optional[str] = None, + scope: Optional[str] = None, + reservation_to_return: Optional["_models.ReservationToReturn"] = None, + return_reason: 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 RefundResponseProperties(_Model): + """The refund properties of reservation. + + :ivar session_id: Refund session identifier. + :vartype session_id: str + :ivar quantity: Quantity to be returned. + :vartype quantity: int + :ivar billing_refund_amount: Pricing information containing the amount and the currency code. + :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price + :ivar pricing_refund_amount: Pricing information containing the amount and the currency code. + :vartype pricing_refund_amount: ~azure.mgmt.reservations.models.Price + :ivar policy_result: Refund policy result. + :vartype policy_result: ~azure.mgmt.reservations.models.RefundPolicyResult + :ivar billing_information: billing information. + :vartype billing_information: ~azure.mgmt.reservations.models.RefundBillingInformation + """ + + session_id: Optional[str] = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """Refund session identifier.""" + quantity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quantity to be returned.""" + billing_refund_amount: Optional["_models.Price"] = rest_field( + name="billingRefundAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + pricing_refund_amount: Optional["_models.Price"] = rest_field( + name="pricingRefundAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + policy_result: Optional["_models.RefundPolicyResult"] = rest_field( + name="policyResult", visibility=["read", "create", "update", "delete", "query"] + ) + """Refund policy result.""" + billing_information: Optional["_models.RefundBillingInformation"] = rest_field( + name="billingInformation", visibility=["read", "create", "update", "delete", "query"] + ) + """billing information.""" + + @overload + def __init__( + self, + *, + session_id: Optional[str] = None, + quantity: Optional[int] = None, + billing_refund_amount: Optional["_models.Price"] = None, + pricing_refund_amount: Optional["_models.Price"] = None, + policy_result: Optional["_models.RefundPolicyResult"] = None, + billing_information: Optional["_models.RefundBillingInformation"] = None, + ) -> 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 RenewPropertiesResponse(_Model): + """The renew properties for a reservation. + + :ivar purchase_properties: The request for reservation purchase. + :vartype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest + :ivar pricing_currency_total: Amount that Microsoft uses for record. Used during refund for + calculating refund limit. Tax is not included. This is locked price 30 days before expiry. + :vartype pricing_currency_total: + ~azure.mgmt.reservations.models.RenewPropertiesResponsePricingCurrencyTotal + :ivar billing_currency_total: Currency and amount that customer will be charged in customer's + local currency for renewal purchase. Tax is not included. + :vartype billing_currency_total: + ~azure.mgmt.reservations.models.RenewPropertiesResponseBillingCurrencyTotal + """ + + purchase_properties: Optional["_models.PurchaseRequest"] = rest_field( + name="purchaseProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """The request for reservation purchase.""" + pricing_currency_total: Optional["_models.RenewPropertiesResponsePricingCurrencyTotal"] = rest_field( + name="pricingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is + not included. This is locked price 30 days before expiry.""" + billing_currency_total: Optional["_models.RenewPropertiesResponseBillingCurrencyTotal"] = rest_field( + name="billingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Currency and amount that customer will be charged in customer's local currency for renewal + purchase. Tax is not included.""" + + @overload + def __init__( + self, + *, + purchase_properties: Optional["_models.PurchaseRequest"] = None, + pricing_currency_total: Optional["_models.RenewPropertiesResponsePricingCurrencyTotal"] = None, + billing_currency_total: Optional["_models.RenewPropertiesResponseBillingCurrencyTotal"] = 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 RenewPropertiesResponseBillingCurrencyTotal(_Model): # pylint: disable=name-too-long + """Currency and amount that customer will be charged in customer's local currency for renewal + purchase. Tax is not included. + + :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase + record. + :vartype currency_code: str + :ivar amount: + :vartype amount: float + """ + + currency_code: Optional[str] = rest_field( + name="currencyCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The ISO 4217 3-letter currency code for the currency used by this purchase record.""" + amount: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + currency_code: Optional[str] = None, + amount: 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 RenewPropertiesResponsePricingCurrencyTotal(_Model): # pylint: disable=name-too-long + """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is + not included. This is locked price 30 days before expiry. + + :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase + record. + :vartype currency_code: str + :ivar amount: + :vartype amount: float + """ + + currency_code: Optional[str] = rest_field( + name="currencyCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The ISO 4217 3-letter currency code for the currency used by this purchase record.""" + amount: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + currency_code: Optional[str] = None, + amount: 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 ReservationMergeProperties(_Model): + """Properties of reservation merge. + + :ivar merge_destination: Reservation resource id Created due to the merge. Format of the + resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype merge_destination: str + :ivar merge_sources: Resource ids of the source reservation's merged to form this reservation. + Format of the resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype merge_sources: list[str] + """ + + merge_destination: Optional[str] = rest_field( + name="mergeDestination", visibility=["read", "create", "update", "delete", "query"] + ) + """Reservation resource id Created due to the merge. Format of the resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + merge_sources: Optional[list[str]] = rest_field( + name="mergeSources", visibility=["read", "create", "update", "delete", "query"] + ) + """Resource ids of the source reservation's merged to form this reservation. Format of the + resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + + @overload + def __init__( + self, + *, + merge_destination: Optional[str] = None, + merge_sources: 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 ReservationOrderBillingPlanInformation(_Model): + """Information describing the type of billing plan for this reservation. + + :ivar pricing_currency_total: Amount of money to be paid for the Order. Tax is not included. + :vartype pricing_currency_total: ~azure.mgmt.reservations.models.Price + :ivar start_date: Date when the billing plan has started. + :vartype start_date: ~datetime.date + :ivar next_payment_due_date: For recurring billing plans, indicates the date when next payment + will be processed. Null when total is paid off. + :vartype next_payment_due_date: ~datetime.date + :ivar transactions: + :vartype transactions: list[~azure.mgmt.reservations.models.PaymentDetail] + """ + + pricing_currency_total: Optional["_models.Price"] = rest_field( + name="pricingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Amount of money to be paid for the Order. Tax is not included.""" + start_date: Optional[datetime.date] = rest_field( + name="startDate", visibility=["read", "create", "update", "delete", "query"] + ) + """Date when the billing plan has started.""" + next_payment_due_date: Optional[datetime.date] = rest_field( + name="nextPaymentDueDate", visibility=["read", "create", "update", "delete", "query"] + ) + """For recurring billing plans, indicates the date when next payment will be processed. Null when + total is paid off.""" + transactions: Optional[list["_models.PaymentDetail"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + pricing_currency_total: Optional["_models.Price"] = None, + start_date: Optional[datetime.date] = None, + next_payment_due_date: Optional[datetime.date] = None, + transactions: Optional[list["_models.PaymentDetail"]] = 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 ReservationOrderProperties(_Model): + """Properties of a reservation order. + + :ivar display_name: Friendly name for user to easily identified the reservation. + :vartype display_name: str + :ivar request_date_time: This is the DateTime when the reservation was initially requested for + purchase. + :vartype request_date_time: ~datetime.datetime + :ivar created_date_time: This is the DateTime when the reservation was created. + :vartype created_date_time: ~datetime.datetime + :ivar expiry_date: This is the date when the reservation will expire. + :vartype expiry_date: ~datetime.date + :ivar expiry_date_time: This is the date-time when the reservation will expire. + :vartype expiry_date_time: ~datetime.datetime + :ivar benefit_start_time: This is the DateTime when the reservation benefit started. + :vartype benefit_start_time: ~datetime.datetime + :ivar original_quantity: Total Quantity of the skus purchased in the reservation. + :vartype original_quantity: int + :ivar term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". + :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm + :ivar provisioning_state: Current state of the reservation. Known values are: "Creating", + "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", + "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and + "Merged". + :vartype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState + :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". + :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan + :ivar plan_information: Information describing the type of billing plan for this reservation. + :vartype plan_information: + ~azure.mgmt.reservations.models.ReservationOrderBillingPlanInformation + :ivar reservations: + :vartype reservations: list[~azure.mgmt.reservations.models.ReservationResponse] + :ivar review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be + reviewed. + :vartype review_date_time: ~datetime.datetime + """ + + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """Friendly name for user to easily identified the reservation.""" + request_date_time: Optional[datetime.datetime] = rest_field( + name="requestDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the DateTime when the reservation was initially requested for purchase.""" + created_date_time: Optional[datetime.datetime] = rest_field( + name="createdDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the DateTime when the reservation was created.""" + expiry_date: Optional[datetime.date] = rest_field( + name="expiryDate", visibility=["read", "create", "update", "delete", "query"] + ) + """This is the date when the reservation will expire.""" + expiry_date_time: Optional[datetime.datetime] = rest_field( + name="expiryDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the date-time when the reservation will expire.""" + benefit_start_time: Optional[datetime.datetime] = rest_field( + name="benefitStartTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the DateTime when the reservation benefit started.""" + original_quantity: Optional[int] = rest_field( + name="originalQuantity", visibility=["read", "create", "update", "delete", "query"] + ) + """Total Quantity of the skus purchased in the reservation.""" + term: Optional[Union[str, "_models.ReservationTerm"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Represent the term of reservation. Known values are: \"P1Y\", \"P3Y\", and \"P5Y\".""" + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read", "create", "update", "delete", "query"] + ) + """Current state of the reservation. Known values are: \"Creating\", \"PendingResourceHold\", + \"ConfirmedResourceHold\", \"PendingBilling\", \"ConfirmedBilling\", \"Created\", + \"Succeeded\", \"Cancelled\", \"Expired\", \"BillingFailed\", \"Failed\", \"Split\", and + \"Merged\".""" + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = rest_field( + name="billingPlan", visibility=["read", "create", "update", "delete", "query"] + ) + """Represent the billing plans. Known values are: \"Upfront\" and \"Monthly\".""" + plan_information: Optional["_models.ReservationOrderBillingPlanInformation"] = rest_field( + name="planInformation", visibility=["read", "create", "update", "delete", "query"] + ) + """Information describing the type of billing plan for this reservation.""" + reservations: Optional[list["_models.ReservationResponse"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + review_date_time: Optional[datetime.datetime] = rest_field( + name="reviewDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the date-time when the Azure Hybrid Benefit needs to be reviewed.""" + + @overload + def __init__( + self, + *, + display_name: Optional[str] = None, + request_date_time: Optional[datetime.datetime] = None, + created_date_time: Optional[datetime.datetime] = None, + expiry_date: Optional[datetime.date] = None, + expiry_date_time: Optional[datetime.datetime] = None, + benefit_start_time: Optional[datetime.datetime] = None, + original_quantity: Optional[int] = None, + term: Optional[Union[str, "_models.ReservationTerm"]] = None, + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, + plan_information: Optional["_models.ReservationOrderBillingPlanInformation"] = None, + reservations: Optional[list["_models.ReservationResponse"]] = None, + review_date_time: 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 ReservationOrderResponse(ProxyResource): + """Details of a reservation order being returned. + + :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.reservations.models.SystemData + :ivar properties: Properties of a reservation order. + :vartype properties: ~azure.mgmt.reservations.models.ReservationOrderProperties + :ivar etag: + :vartype etag: int + """ + + properties: Optional["_models.ReservationOrderProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of a reservation order.""" + etag: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + __flattened_items = [ + "display_name", + "request_date_time", + "created_date_time", + "expiry_date", + "expiry_date_time", + "benefit_start_time", + "original_quantity", + "term", + "provisioning_state", + "billing_plan", + "plan_information", + "reservations", + "review_date_time", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.ReservationOrderProperties"] = None, + etag: Optional[int] = 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 ReservationResponse(ProxyResource): + """The definition of the reservation. + + :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.reservations.models.SystemData + :ivar properties: The properties associated to this reservation. + :vartype properties: ~azure.mgmt.reservations.models.ReservationsProperties + :ivar location: The Azure region where the reserved resource lives. + :vartype location: str + :ivar etag: + :vartype etag: int + :ivar sku: The sku information associated to this reservation. + :vartype sku: ~azure.mgmt.reservations.models.SkuName + :ivar kind: Resource Provider type to be reserved. Default value is "Microsoft.Compute". + :vartype kind: str + """ + + properties: Optional["_models.ReservationsProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The properties associated to this reservation.""" + location: Optional[str] = rest_field(visibility=["read", "create"]) + """The Azure region where the reserved resource lives.""" + etag: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + sku: Optional["_models.SkuName"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The sku information associated to this reservation.""" + kind: Optional[Literal["Microsoft.Compute"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Resource Provider type to be reserved. Default value is \"Microsoft.Compute\".""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.ReservationsProperties"] = None, + location: Optional[str] = None, + etag: Optional[int] = None, + sku: Optional["_models.SkuName"] = None, + kind: Optional[Literal["Microsoft.Compute"]] = 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 ReservationSplitProperties(_Model): + """Properties of reservation split. + + :ivar split_destinations: List of destination resource id that are created due to split. Format + of the resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype split_destinations: list[str] + :ivar split_source: Resource id of the reservation from which this is split. Format of the + resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype split_source: str + """ + + split_destinations: Optional[list[str]] = rest_field( + name="splitDestinations", visibility=["read", "create", "update", "delete", "query"] + ) + """List of destination resource id that are created due to split. Format of the resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + split_source: Optional[str] = rest_field( + name="splitSource", visibility=["read", "create", "update", "delete", "query"] + ) + """Resource id of the reservation from which this is split. Format of the resource id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + + @overload + def __init__( + self, + *, + split_destinations: Optional[list[str]] = None, + split_source: 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 ReservationsProperties(_Model): + """The properties of the reservations. + + :ivar reserved_resource_type: The type of the resource that is being reserved. Known values + are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", + "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", + "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", + "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", + "SqlEdge", and "VirtualMachineSoftware". + :vartype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType + :ivar instance_flexibility: Allows reservation discount to be applied across skus within the + same auto fit group. Not all skus support instance size flexibility. Known values are: "On" and + "Off". + :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility + :ivar display_name: Friendly name for user to easily identify the reservation. + :vartype display_name: str + :ivar applied_scopes: The list of applied scopes. + :vartype applied_scopes: list[str] + :ivar applied_scope_type: The applied scope type. Known values are: "Single", "Shared", and + "ManagementGroup". + :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType + :ivar archived: Indicates if the reservation is archived. + :vartype archived: bool + :ivar capabilities: Capabilities of the reservation. + :vartype capabilities: str + :ivar quantity: Quantity of the skus that are part of the reservation. Must be greater than + zero. + :vartype quantity: int + :ivar provisioning_state: Current state of the reservation. Known values are: "Creating", + "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", + "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and + "Merged". + :vartype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState + :ivar effective_date_time: DateTime of the reservation starting when this version is effective + from. + :vartype effective_date_time: ~datetime.datetime + :ivar benefit_start_time: This is the DateTime when the reservation benefit started. + :vartype benefit_start_time: ~datetime.datetime + :ivar last_updated_date_time: DateTime of the last time the reservation was updated. + :vartype last_updated_date_time: ~datetime.datetime + :ivar expiry_date: This is the date when the reservation will expire. + :vartype expiry_date: ~datetime.date + :ivar expiry_date_time: This is the date-time when the reservation will expire. + :vartype expiry_date_time: ~datetime.datetime + :ivar review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be + reviewed. + :vartype review_date_time: ~datetime.datetime + :ivar sku_description: Description of the sku in english. + :vartype sku_description: str + :ivar extended_status_info: The message giving detailed information about the status code. + :vartype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo + :ivar billing_plan: The billing plan options available for this sku. Known values are: + "Upfront" and "Monthly". + :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan + :ivar display_provisioning_state: The provisioning state of the reservation for display, e.g. + Succeeded. + :vartype display_provisioning_state: str + :ivar provisioning_sub_state: The provisioning sub-state of the reservation, e.g. Succeeded. + :vartype provisioning_sub_state: str + :ivar purchase_date: This is the date when the reservation was purchased. + :vartype purchase_date: ~datetime.date + :ivar purchase_date_time: This is the date-time when the reservation was purchased. + :vartype purchase_date_time: ~datetime.datetime + :ivar split_properties: Properties of reservation split. + :vartype split_properties: ~azure.mgmt.reservations.models.ReservationSplitProperties + :ivar merge_properties: Properties of reservation merge. + :vartype merge_properties: ~azure.mgmt.reservations.models.ReservationMergeProperties + :ivar swap_properties: Properties of reservation swap. + :vartype swap_properties: ~azure.mgmt.reservations.models.ReservationSwapProperties + :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not + applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is + ManagementGroup. + :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties + :ivar billing_scope_id: Subscription that will be charged for purchasing reservation or savings + plan. + :vartype billing_scope_id: str + :ivar renew: Setting this to true will automatically purchase a new reservation on the + expiration date time. + :vartype renew: bool + :ivar renew_source: Reservation Id of the reservation from which this reservation is renewed. + Format of the resource Id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype renew_source: str + :ivar renew_destination: Reservation Id of the reservation which is purchased because of renew. + Format of the resource Id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype renew_destination: str + :ivar renew_properties: The renew properties for a reservation. + :vartype renew_properties: ~azure.mgmt.reservations.models.RenewPropertiesResponse + :ivar term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". + :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm + :ivar user_friendly_applied_scope_type: The applied scope type of the reservation for display, + e.g. Shared. + :vartype user_friendly_applied_scope_type: str + :ivar user_friendly_renew_state: The renew state of the reservation for display, e.g. On. + :vartype user_friendly_renew_state: str + :ivar utilization: Reservation utilization. + :vartype utilization: ~azure.mgmt.reservations.models.ReservationsPropertiesUtilization + """ + + reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = rest_field( + name="reservedResourceType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of the resource that is being reserved. Known values are: \"VirtualMachines\", + \"SqlDatabases\", \"SuseLinux\", \"CosmosDb\", \"RedHat\", \"SqlDataWarehouse\", + \"VMwareCloudSimple\", \"RedHatOsa\", \"Databricks\", \"AppService\", \"ManagedDisk\", + \"BlockBlob\", \"RedisCache\", \"AzureDataExplorer\", \"MySql\", \"MariaDb\", \"PostgreSql\", + \"DedicatedHost\", \"SapHana\", \"SqlAzureHybridBenefit\", \"AVS\", \"DataFactory\", + \"NetAppStorage\", \"AzureFiles\", \"SqlEdge\", and \"VirtualMachineSoftware\".""" + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = rest_field( + name="instanceFlexibility", visibility=["read", "create", "update", "delete", "query"] + ) + """Allows reservation discount to be applied across skus within the same auto fit group. Not all + skus support instance size flexibility. Known values are: \"On\" and \"Off\".""" + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """Friendly name for user to easily identify the reservation.""" + applied_scopes: Optional[list[str]] = rest_field( + name="appliedScopes", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of applied scopes.""" + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = rest_field( + name="appliedScopeType", visibility=["read", "create", "update", "delete", "query"] + ) + """The applied scope type. Known values are: \"Single\", \"Shared\", and \"ManagementGroup\".""" + archived: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Indicates if the reservation is archived.""" + capabilities: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Capabilities of the reservation.""" + quantity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quantity of the skus that are part of the reservation. Must be greater than zero.""" + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read", "create", "update", "delete", "query"] + ) + """Current state of the reservation. Known values are: \"Creating\", \"PendingResourceHold\", + \"ConfirmedResourceHold\", \"PendingBilling\", \"ConfirmedBilling\", \"Created\", + \"Succeeded\", \"Cancelled\", \"Expired\", \"BillingFailed\", \"Failed\", \"Split\", and + \"Merged\".""" + effective_date_time: Optional[datetime.datetime] = rest_field( + name="effectiveDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """DateTime of the reservation starting when this version is effective from.""" + benefit_start_time: Optional[datetime.datetime] = rest_field( + name="benefitStartTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the DateTime when the reservation benefit started.""" + last_updated_date_time: Optional[datetime.datetime] = rest_field( + name="lastUpdatedDateTime", visibility=["read"], format="rfc3339" + ) + """DateTime of the last time the reservation was updated.""" + expiry_date: Optional[datetime.date] = rest_field( + name="expiryDate", visibility=["read", "create", "update", "delete", "query"] + ) + """This is the date when the reservation will expire.""" + expiry_date_time: Optional[datetime.datetime] = rest_field( + name="expiryDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the date-time when the reservation will expire.""" + review_date_time: Optional[datetime.datetime] = rest_field( + name="reviewDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the date-time when the Azure Hybrid Benefit needs to be reviewed.""" + sku_description: Optional[str] = rest_field( + name="skuDescription", visibility=["read", "create", "update", "delete", "query"] + ) + """Description of the sku in english.""" + extended_status_info: Optional["_models.ExtendedStatusInfo"] = rest_field( + name="extendedStatusInfo", visibility=["read", "create", "update", "delete", "query"] + ) + """The message giving detailed information about the status code.""" + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = rest_field( + name="billingPlan", visibility=["read", "create", "update", "delete", "query"] + ) + """The billing plan options available for this sku. Known values are: \"Upfront\" and \"Monthly\".""" + display_provisioning_state: Optional[str] = rest_field(name="displayProvisioningState", visibility=["read"]) + """The provisioning state of the reservation for display, e.g. Succeeded.""" + provisioning_sub_state: Optional[str] = rest_field(name="provisioningSubState", visibility=["read"]) + """The provisioning sub-state of the reservation, e.g. Succeeded.""" + purchase_date: Optional[datetime.date] = rest_field( + name="purchaseDate", visibility=["read", "create", "update", "delete", "query"] + ) + """This is the date when the reservation was purchased.""" + purchase_date_time: Optional[datetime.datetime] = rest_field( + name="purchaseDateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """This is the date-time when the reservation was purchased.""" + split_properties: Optional["_models.ReservationSplitProperties"] = rest_field( + name="splitProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of reservation split.""" + merge_properties: Optional["_models.ReservationMergeProperties"] = rest_field( + name="mergeProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of reservation merge.""" + swap_properties: Optional["_models.ReservationSwapProperties"] = rest_field( + name="swapProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of reservation swap.""" + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = rest_field( + name="appliedScopeProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties specific to applied scope type. Not required if not applicable. Required and need to + provide tenantId and managementGroupId if AppliedScopeType is ManagementGroup.""" + billing_scope_id: Optional[str] = rest_field( + name="billingScopeId", visibility=["read", "create", "update", "delete", "query"] + ) + """Subscription that will be charged for purchasing reservation or savings plan.""" + renew: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Setting this to true will automatically purchase a new reservation on the expiration date time.""" + renew_source: Optional[str] = rest_field( + name="renewSource", visibility=["read", "create", "update", "delete", "query"] + ) + """Reservation Id of the reservation from which this reservation is renewed. Format of the + resource Id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + renew_destination: Optional[str] = rest_field( + name="renewDestination", visibility=["read", "create", "update", "delete", "query"] + ) + """Reservation Id of the reservation which is purchased because of renew. Format of the resource + Id is + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + renew_properties: Optional["_models.RenewPropertiesResponse"] = rest_field( + name="renewProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """The renew properties for a reservation.""" + term: Optional[Union[str, "_models.ReservationTerm"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Represent the term of reservation. Known values are: \"P1Y\", \"P3Y\", and \"P5Y\".""" + user_friendly_applied_scope_type: Optional[str] = rest_field( + name="userFriendlyAppliedScopeType", visibility=["read"] + ) + """The applied scope type of the reservation for display, e.g. Shared.""" + user_friendly_renew_state: Optional[str] = rest_field(name="userFriendlyRenewState", visibility=["read"]) + """The renew state of the reservation for display, e.g. On.""" + utilization: Optional["_models.ReservationsPropertiesUtilization"] = rest_field(visibility=["read"]) + """Reservation utilization.""" + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None, + instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, + display_name: Optional[str] = None, + applied_scopes: Optional[list[str]] = None, + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, + archived: Optional[bool] = None, + capabilities: Optional[str] = None, + quantity: Optional[int] = None, + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, + effective_date_time: Optional[datetime.datetime] = None, + benefit_start_time: Optional[datetime.datetime] = None, + expiry_date: Optional[datetime.date] = None, + expiry_date_time: Optional[datetime.datetime] = None, + review_date_time: Optional[datetime.datetime] = None, + sku_description: Optional[str] = None, + extended_status_info: Optional["_models.ExtendedStatusInfo"] = None, + billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, + purchase_date: Optional[datetime.date] = None, + purchase_date_time: Optional[datetime.datetime] = None, + split_properties: Optional["_models.ReservationSplitProperties"] = None, + merge_properties: Optional["_models.ReservationMergeProperties"] = None, + swap_properties: Optional["_models.ReservationSwapProperties"] = None, + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, + billing_scope_id: Optional[str] = None, + renew: Optional[bool] = None, + renew_source: Optional[str] = None, + renew_destination: Optional[str] = None, + renew_properties: Optional["_models.RenewPropertiesResponse"] = None, + term: Optional[Union[str, "_models.ReservationTerm"]] = 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 ReservationsPropertiesUtilization(_Model): + """Reservation utilization. + + :ivar trend: last 7 day utilization trend for a reservation. + :vartype trend: str + :ivar aggregates: The array of aggregates of a reservation's utilization. + :vartype aggregates: list[~azure.mgmt.reservations.models.ReservationUtilizationAggregates] + """ + + trend: Optional[str] = rest_field(visibility=["read"]) + """last 7 day utilization trend for a reservation.""" + aggregates: Optional[list["_models.ReservationUtilizationAggregates"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The array of aggregates of a reservation's utilization.""" + + @overload + def __init__( + self, + *, + aggregates: Optional[list["_models.ReservationUtilizationAggregates"]] = 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 ReservationSummary(_Model): + """The roll up count summary of reservations in each state. + + :ivar succeeded_count: The number of reservation in Succeeded state. + :vartype succeeded_count: float + :ivar failed_count: The number of reservation in Failed state. + :vartype failed_count: float + :ivar expiring_count: The number of reservation in Expiring state. + :vartype expiring_count: float + :ivar expired_count: The number of reservation in Expired state. + :vartype expired_count: float + :ivar pending_count: The number of reservation in Pending state. + :vartype pending_count: float + :ivar cancelled_count: The number of reservation in Cancelled state. + :vartype cancelled_count: float + :ivar processing_count: The number of reservation in Processing state. + :vartype processing_count: float + :ivar warning_count: The number of reservation in Warning state. + :vartype warning_count: float + :ivar no_benefit_count: The number of reservation in NoBenefit state. + :vartype no_benefit_count: float + """ + + succeeded_count: Optional[float] = rest_field(name="succeededCount", visibility=["read"]) + """The number of reservation in Succeeded state.""" + failed_count: Optional[float] = rest_field(name="failedCount", visibility=["read"]) + """The number of reservation in Failed state.""" + expiring_count: Optional[float] = rest_field(name="expiringCount", visibility=["read"]) + """The number of reservation in Expiring state.""" + expired_count: Optional[float] = rest_field(name="expiredCount", visibility=["read"]) + """The number of reservation in Expired state.""" + pending_count: Optional[float] = rest_field(name="pendingCount", visibility=["read"]) + """The number of reservation in Pending state.""" + cancelled_count: Optional[float] = rest_field(name="cancelledCount", visibility=["read"]) + """The number of reservation in Cancelled state.""" + processing_count: Optional[float] = rest_field(name="processingCount", visibility=["read"]) + """The number of reservation in Processing state.""" + warning_count: Optional[float] = rest_field(name="warningCount", visibility=["read"]) + """The number of reservation in Warning state.""" + no_benefit_count: Optional[float] = rest_field(name="noBenefitCount", visibility=["read"]) + """The number of reservation in NoBenefit state.""" + + +class ReservationSwapProperties(_Model): + """Properties of reservation swap. + + :ivar swap_source: Resource id of the source reservation that gets swapped. Format of the + resource id is + /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype swap_source: str + :ivar swap_destination: Reservation resource id that the original resource gets swapped to. + Format of the resource id is + /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype swap_destination: str + """ + + swap_source: Optional[str] = rest_field( + name="swapSource", visibility=["read", "create", "update", "delete", "query"] + ) + """Resource id of the source reservation that gets swapped. Format of the resource id is + /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + swap_destination: Optional[str] = rest_field( + name="swapDestination", visibility=["read", "create", "update", "delete", "query"] + ) + """Reservation resource id that the original resource gets swapped to. Format of the resource id + is + /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + + @overload + def __init__( + self, + *, + swap_source: Optional[str] = None, + swap_destination: 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 ReservationToExchange(_Model): + """Reservation refund details. + + :ivar reservation_id: Fully qualified id of the reservation being returned. + :vartype reservation_id: str + :ivar quantity: Quantity to be returned. + :vartype quantity: int + :ivar billing_refund_amount: Pricing information containing the amount and the currency code. + :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_information: billing information. + :vartype billing_information: ~azure.mgmt.reservations.models.BillingInformation + """ + + reservation_id: Optional[str] = rest_field( + name="reservationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified id of the reservation being returned.""" + quantity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quantity to be returned.""" + billing_refund_amount: Optional["_models.Price"] = rest_field( + name="billingRefundAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + billing_information: Optional["_models.BillingInformation"] = rest_field( + name="billingInformation", visibility=["read", "create", "update", "delete", "query"] + ) + """billing information.""" + + @overload + def __init__( + self, + *, + reservation_id: Optional[str] = None, + quantity: Optional[int] = None, + billing_refund_amount: Optional["_models.Price"] = None, + billing_information: Optional["_models.BillingInformation"] = 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 ReservationToPurchaseCalculateExchange(_Model): + """Reservation purchase details. + + :ivar properties: The request for reservation purchase. + :vartype properties: ~azure.mgmt.reservations.models.PurchaseRequest + :ivar billing_currency_total: Pricing information containing the amount and the currency code. + :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price + """ + + properties: Optional["_models.PurchaseRequest"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The request for reservation purchase.""" + billing_currency_total: Optional["_models.Price"] = rest_field( + name="billingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.PurchaseRequest"] = None, + billing_currency_total: Optional["_models.Price"] = 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 ReservationToPurchaseExchange(_Model): + """Reservation purchase details. + + :ivar reservation_order_id: Fully qualified id of the reservationOrder being purchased. + :vartype reservation_order_id: str + :ivar reservation_id: Fully qualified id of the reservation being purchased. This value is only + guaranteed to be non-null if the purchase is successful. + :vartype reservation_id: str + :ivar properties: The request for reservation purchase. + :vartype properties: ~azure.mgmt.reservations.models.PurchaseRequest + :ivar billing_currency_total: Pricing information containing the amount and the currency code. + :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price + :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", + "Cancelled", and "Pending". + :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus + """ + + reservation_order_id: Optional[str] = rest_field( + name="reservationOrderId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified id of the reservationOrder being purchased.""" + reservation_id: Optional[str] = rest_field( + name="reservationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified id of the reservation being purchased. This value is only guaranteed to be + non-null if the purchase is successful.""" + properties: Optional["_models.PurchaseRequest"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The request for reservation purchase.""" + billing_currency_total: Optional["_models.Price"] = rest_field( + name="billingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + status: Optional[Union[str, "_models.OperationStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Status of the individual operation. Known values are: \"Succeeded\", \"Failed\", \"Cancelled\", + and \"Pending\".""" + + @overload + def __init__( + self, + *, + reservation_order_id: Optional[str] = None, + reservation_id: Optional[str] = None, + properties: Optional["_models.PurchaseRequest"] = None, + billing_currency_total: Optional["_models.Price"] = None, + status: Optional[Union[str, "_models.OperationStatus"]] = 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 ReservationToReturn(_Model): + """Reservation to return. + + :ivar reservation_id: Fully qualified identifier of the reservation being returned. + :vartype reservation_id: str + :ivar quantity: Quantity to be returned. Must be greater than zero. + :vartype quantity: int + """ + + reservation_id: Optional[str] = rest_field( + name="reservationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified identifier of the reservation being returned.""" + quantity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quantity to be returned. Must be greater than zero.""" + + @overload + def __init__( + self, + *, + reservation_id: Optional[str] = None, + quantity: Optional[int] = 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 ReservationToReturnForExchange(_Model): + """Reservation refund details. + + :ivar reservation_id: Fully qualified id of the reservation being returned. + :vartype reservation_id: str + :ivar quantity: Quantity to be returned. + :vartype quantity: int + :ivar billing_refund_amount: Pricing information containing the amount and the currency code. + :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price + :ivar billing_information: billing information. + :vartype billing_information: ~azure.mgmt.reservations.models.BillingInformation + :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", + "Cancelled", and "Pending". + :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus + """ + + reservation_id: Optional[str] = rest_field( + name="reservationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified id of the reservation being returned.""" + quantity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quantity to be returned.""" + billing_refund_amount: Optional["_models.Price"] = rest_field( + name="billingRefundAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + billing_information: Optional["_models.BillingInformation"] = rest_field( + name="billingInformation", visibility=["read", "create", "update", "delete", "query"] + ) + """billing information.""" + status: Optional[Union[str, "_models.OperationStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Status of the individual operation. Known values are: \"Succeeded\", \"Failed\", \"Cancelled\", + and \"Pending\".""" + + @overload + def __init__( + self, + *, + reservation_id: Optional[str] = None, + quantity: Optional[int] = None, + billing_refund_amount: Optional["_models.Price"] = None, + billing_information: Optional["_models.BillingInformation"] = None, + status: Optional[Union[str, "_models.OperationStatus"]] = 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 ReservationUtilizationAggregates(_Model): + """The aggregate values of reservation utilization. + + :ivar grain: The grain of the aggregate. + :vartype grain: float + :ivar grain_unit: The grain unit of the aggregate. + :vartype grain_unit: str + :ivar value: The aggregate value. + :vartype value: float + :ivar value_unit: The aggregate value unit. + :vartype value_unit: str + """ + + grain: Optional[float] = rest_field(visibility=["read"]) + """The grain of the aggregate.""" + grain_unit: Optional[str] = rest_field(name="grainUnit", visibility=["read"]) + """The grain unit of the aggregate.""" + value: Optional[float] = rest_field(visibility=["read"]) + """The aggregate value.""" + value_unit: Optional[str] = rest_field(name="valueUnit", visibility=["read"]) + """The aggregate value unit.""" + + +class ResourceName(_Model): + """Resource name provided by the resource provider. Use this property for quotaRequest parameter. + + :ivar value: Resource name. + :vartype value: str + :ivar localized_value: Resource display localized name. + :vartype localized_value: str + """ + + value: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource name.""" + localized_value: Optional[str] = rest_field(name="localizedValue", visibility=["read"]) + """Resource display localized name.""" + + @overload + def __init__( + self, + *, + value: 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 SavingsPlanPurchaseRequest(_Model): + """Request body for savings plan purchase. + + :ivar sku: The name of sku. + :vartype sku: ~azure.mgmt.reservations.models.SkuName + :ivar properties: Properties of a savings plan purchase. + :vartype properties: ~azure.mgmt.reservations.models.SavingsPlanPurchaseRequestProperties + """ + + sku: Optional["_models.SkuName"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of sku.""" + properties: Optional["_models.SavingsPlanPurchaseRequestProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of a savings plan purchase.""" + + __flattened_items = [ + "display_name", + "billing_scope_id", + "term", + "billing_plan", + "applied_scope_type", + "applied_scope_properties", + "commitment", + ] + + @overload + def __init__( + self, + *, + sku: Optional["_models.SkuName"] = None, + properties: Optional["_models.SavingsPlanPurchaseRequestProperties"] = 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 SavingsPlanPurchaseRequestProperties(_Model): + """Properties of a savings plan purchase. + + :ivar display_name: Friendly name of the savings plan. + :vartype display_name: str + :ivar billing_scope_id: Subscription that will be charged for purchasing reservation or savings + plan. + :vartype billing_scope_id: str + :ivar term: Represent savings plan term in ISO 8601 format. Known values are: "P1Y" and "P3Y". + :vartype term: str or ~azure.mgmt.reservations.models.SavingsPlanTerm + :ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly + billing plans. "P1M" + :vartype billing_plan: str or ~azure.mgmt.reservations.models.BillingPlan + :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and + "ManagementGroup". + :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType + :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not + applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is + ManagementGroup. + :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties + :ivar commitment: Commitment towards the benefit. + :vartype commitment: ~azure.mgmt.reservations.models.Commitment + """ + + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """Friendly name of the savings plan.""" + billing_scope_id: Optional[str] = rest_field( + name="billingScopeId", visibility=["read", "create", "update", "delete", "query"] + ) + """Subscription that will be charged for purchasing reservation or savings plan.""" + term: Optional[Union[str, "_models.SavingsPlanTerm"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Represent savings plan term in ISO 8601 format. Known values are: \"P1Y\" and \"P3Y\".""" + billing_plan: Optional[Union[str, "_models.BillingPlan"]] = rest_field( + name="billingPlan", visibility=["read", "create", "update", "delete", "query"] + ) + """Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. + \"P1M\"""" + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = rest_field( + name="appliedScopeType", visibility=["read", "create", "update", "delete", "query"] + ) + """Type of the Applied Scope. Known values are: \"Single\", \"Shared\", and \"ManagementGroup\".""" + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = rest_field( + name="appliedScopeProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Properties specific to applied scope type. Not required if not applicable. Required and need to + provide tenantId and managementGroupId if AppliedScopeType is ManagementGroup.""" + commitment: Optional["_models.Commitment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Commitment towards the benefit.""" + + @overload + def __init__( + self, + *, + display_name: Optional[str] = None, + billing_scope_id: Optional[str] = None, + term: Optional[Union[str, "_models.SavingsPlanTerm"]] = None, + billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None, + applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, + applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, + commitment: Optional["_models.Commitment"] = 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 SavingsPlanToPurchaseCalculateExchange(_Model): + """Savings plan purchase details. + + :ivar properties: Request body for savings plan purchase. + :vartype properties: ~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest + :ivar billing_currency_total: Pricing information containing the amount and the currency code. + :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price + """ + + properties: Optional["_models.SavingsPlanPurchaseRequest"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Request body for savings plan purchase.""" + billing_currency_total: Optional["_models.Price"] = rest_field( + name="billingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.SavingsPlanPurchaseRequest"] = None, + billing_currency_total: Optional["_models.Price"] = 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 SavingsPlanToPurchaseExchange(_Model): + """Savings plan purchase details. + + :ivar savings_plan_order_id: Fully qualified id of the savings plan order being purchased. + :vartype savings_plan_order_id: str + :ivar savings_plan_id: Fully qualified id of the savings plan being purchased. This value is + only guaranteed to be non-null if the purchase is successful. + :vartype savings_plan_id: str + :ivar properties: Request body for savings plan purchase. + :vartype properties: ~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest + :ivar billing_currency_total: Pricing information containing the amount and the currency code. + :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price + :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", + "Cancelled", and "Pending". + :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus + """ + + savings_plan_order_id: Optional[str] = rest_field( + name="savingsPlanOrderId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified id of the savings plan order being purchased.""" + savings_plan_id: Optional[str] = rest_field( + name="savingsPlanId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified id of the savings plan being purchased. This value is only guaranteed to be + non-null if the purchase is successful.""" + properties: Optional["_models.SavingsPlanPurchaseRequest"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Request body for savings plan purchase.""" + billing_currency_total: Optional["_models.Price"] = rest_field( + name="billingCurrencyTotal", visibility=["read", "create", "update", "delete", "query"] + ) + """Pricing information containing the amount and the currency code.""" + status: Optional[Union[str, "_models.OperationStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Status of the individual operation. Known values are: \"Succeeded\", \"Failed\", \"Cancelled\", + and \"Pending\".""" + + @overload + def __init__( + self, + *, + savings_plan_order_id: Optional[str] = None, + savings_plan_id: Optional[str] = None, + properties: Optional["_models.SavingsPlanPurchaseRequest"] = None, + billing_currency_total: Optional["_models.Price"] = None, + status: Optional[Union[str, "_models.OperationStatus"]] = 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 ScopeProperties(_Model): + """The scope and whether it is valid. + + :ivar scope: + :vartype scope: str + :ivar valid: + :vartype valid: bool + """ + + scope: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + valid: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + scope: Optional[str] = None, + valid: Optional[bool] = 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 ServiceError(_Model): + """The API error details. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message text. + :vartype message: str + :ivar details: The list of error details. + :vartype details: list[~azure.mgmt.reservations.models.ServiceErrorDetail] + """ + + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error message text.""" + details: Optional[list["_models.ServiceErrorDetail"]] = rest_field(visibility=["read"]) + """The list of error details.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + message: 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 ServiceErrorDetail(_Model): + """The error details. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """The error message.""" + + +class SkuCapability(_Model): + """Capability of a sku. + + :ivar name: An invariant to describe the feature. + :vartype name: str + :ivar value: An invariant if the feature is measured by quantity. + :vartype value: str + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An invariant to describe the feature.""" + value: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An invariant if the feature is measured by quantity.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + value: 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 SkuName(_Model): + """The name of sku. + + :ivar name: + :vartype name: str + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + name: 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 SkuProperty(_Model): + """Property of a sku. + + :ivar name: An invariant to describe the feature. + :vartype name: str + :ivar value: An invariant if the feature is measured by quantity. + :vartype value: str + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An invariant to describe the feature.""" + value: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An invariant if the feature is measured by quantity.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + value: 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 SkuRestriction(_Model): + """Restriction of a sku. + + :ivar type: The type of restrictions. + :vartype type: str + :ivar values_property: The value of restrictions. If the restriction type is set to location. + This would be different locations where the sku is restricted. + :vartype values_property: list[str] + :ivar reason_code: The reason for restriction. + :vartype reason_code: str + """ + + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The type of restrictions.""" + values_property: Optional[list[str]] = rest_field( + name="values", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="values" + ) + """The value of restrictions. If the restriction type is set to location. This would be different + locations where the sku is restricted.""" + reason_code: Optional[str] = rest_field( + name="reasonCode", visibility=["read", "create", "update", "delete", "query"] + ) + """The reason for restriction.""" + + @overload + def __init__( + self, + *, + type: Optional[str] = None, + values_property: Optional[list[str]] = None, + reason_code: 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 SplitProperties(_Model): + """Properties for reservation split. + + :ivar quantities: List of the quantities in the new reservations to create. + :vartype quantities: list[int] + :ivar reservation_id: Resource id of the reservation to be split. Format of the resource id + should be + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. + :vartype reservation_id: str + """ + + quantities: Optional[list[int]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """List of the quantities in the new reservations to create.""" + reservation_id: Optional[str] = rest_field( + name="reservationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Resource id of the reservation to be split. Format of the resource id should be + /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}.""" + + @overload + def __init__( + self, + *, + quantities: Optional[list[int]] = None, + reservation_id: 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 SplitRequest(_Model): + """The request for reservation split. + + :ivar properties: Properties for reservation split. + :vartype properties: ~azure.mgmt.reservations.models.SplitProperties + """ + + properties: Optional["_models.SplitProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties for reservation split.""" + + __flattened_items = ["quantities", "reservation_id"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.SplitProperties"] = 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 SubRequest(_Model): + """The sub-request submitted with the quota request. + + :ivar limit: Quota (resource limit). + :vartype limit: int + :ivar name: The resource name. + :vartype name: ~azure.mgmt.reservations.models.ResourceName + :ivar resource_type: Resource type for which the quota check was made. + :vartype resource_type: str + :ivar unit: The limit units, such as **count** and **bytes**. Use the unit field provided in + the response of the GET quota operation. + :vartype unit: str + :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", + "Succeeded", "Failed", and "InProgress". + :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState + :ivar message: User-friendly status message. + :vartype message: str + :ivar sub_request_id: Sub request ID for individual request. + :vartype sub_request_id: str + """ + + limit: Optional[int] = rest_field(visibility=["read"]) + """Quota (resource limit).""" + name: Optional["_models.ResourceName"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The resource name.""" + resource_type: Optional[str] = rest_field(name="resourceType", visibility=["read"]) + """Resource type for which the quota check was made.""" + unit: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The limit units, such as **count** and **bytes**. Use the unit field provided in the response + of the GET quota operation.""" + provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = rest_field( + name="provisioningState", visibility=["read", "create", "update", "delete", "query"] + ) + """The quota request status. Known values are: \"Accepted\", \"Invalid\", \"Succeeded\", + \"Failed\", and \"InProgress\".""" + message: Optional[str] = rest_field(visibility=["read"]) + """User-friendly status message.""" + sub_request_id: Optional[str] = rest_field(name="subRequestId", visibility=["read"]) + """Sub request ID for individual request.""" + + @overload + def __init__( + self, + *, + name: Optional["_models.ResourceName"] = None, + unit: Optional[str] = None, + provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = 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 SubscriptionScopeProperties(_Model): + """The scopes checked by the available scope api. + + :ivar scopes: + :vartype scopes: list[~azure.mgmt.reservations.models.ScopeProperties] + """ + + scopes: Optional[list["_models.ScopeProperties"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + scopes: Optional[list["_models.ScopeProperties"]] = 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 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.reservations.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.reservations.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + 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) diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models_py3.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models_py3.py deleted file mode 100644 index 2ee33e288759..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_models_py3.py +++ /dev/null @@ -1,4902 +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 -import sys -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union - -from .. import _serialization - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -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 .. import models as _models -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - - -class AppliedReservationList(_serialization.Model): - """Paginated list of applied reservations. - - :ivar value: - :vartype value: list[str] - :ivar next_link: Url to get the next page of reservations. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[str]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[List[str]] = None, next_link: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword value: - :paramtype value: list[str] - :keyword next_link: Url to get the next page of reservations. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class AppliedReservations(_serialization.Model): - """The response for applied reservations api. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Identifier of the applied reservations. - :vartype id: str - :ivar name: Name of resource. - :vartype name: str - :ivar type: Type of resource. "Microsoft.Capacity/AppliedReservations". - :vartype type: str - :ivar reservation_order_ids: Paginated list of applied reservations. - :vartype reservation_order_ids: ~azure.mgmt.reservations.models.AppliedReservationList - """ - - _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"}, - "reservation_order_ids": {"key": "properties.reservationOrderIds", "type": "AppliedReservationList"}, - } - - def __init__( - self, *, reservation_order_ids: Optional["_models.AppliedReservationList"] = None, **kwargs: Any - ) -> None: - """ - :keyword reservation_order_ids: Paginated list of applied reservations. - :paramtype reservation_order_ids: ~azure.mgmt.reservations.models.AppliedReservationList - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.reservation_order_ids = reservation_order_ids - - -class AppliedScopeProperties(_serialization.Model): - """Properties specific to applied scope type. Not required if not applicable. Required and need to - provide tenantId and managementGroupId if AppliedScopeType is ManagementGroup. - - :ivar tenant_id: Tenant ID where the savings plan should apply benefit. - :vartype tenant_id: str - :ivar management_group_id: Fully-qualified identifier of the management group where the benefit - must be applied. - :vartype management_group_id: str - :ivar subscription_id: Fully-qualified identifier of the subscription. - :vartype subscription_id: str - :ivar resource_group_id: Fully-qualified identifier of the resource group. - :vartype resource_group_id: str - :ivar display_name: Display name. - :vartype display_name: str - """ - - _attribute_map = { - "tenant_id": {"key": "tenantId", "type": "str"}, - "management_group_id": {"key": "managementGroupId", "type": "str"}, - "subscription_id": {"key": "subscriptionId", "type": "str"}, - "resource_group_id": {"key": "resourceGroupId", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - } - - def __init__( - self, - *, - tenant_id: Optional[str] = None, - management_group_id: Optional[str] = None, - subscription_id: Optional[str] = None, - resource_group_id: Optional[str] = None, - display_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword tenant_id: Tenant ID where the savings plan should apply benefit. - :paramtype tenant_id: str - :keyword management_group_id: Fully-qualified identifier of the management group where the - benefit must be applied. - :paramtype management_group_id: str - :keyword subscription_id: Fully-qualified identifier of the subscription. - :paramtype subscription_id: str - :keyword resource_group_id: Fully-qualified identifier of the resource group. - :paramtype resource_group_id: str - :keyword display_name: Display name. - :paramtype display_name: str - """ - super().__init__(**kwargs) - self.tenant_id = tenant_id - self.management_group_id = management_group_id - self.subscription_id = subscription_id - self.resource_group_id = resource_group_id - self.display_name = display_name - - -class AvailableScopeProperties(_serialization.Model): - """The response of available scope api containing scopes and their eligibilities. - - :ivar properties: The scopes checked by the available scope api. - :vartype properties: ~azure.mgmt.reservations.models.SubscriptionScopeProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "SubscriptionScopeProperties"}, - } - - def __init__(self, *, properties: Optional["_models.SubscriptionScopeProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: The scopes checked by the available scope api. - :paramtype properties: ~azure.mgmt.reservations.models.SubscriptionScopeProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class AvailableScopeRequest(_serialization.Model): - """Available scope. - - :ivar properties: Available scope request properties. - :vartype properties: ~azure.mgmt.reservations.models.AvailableScopeRequestProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "AvailableScopeRequestProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.AvailableScopeRequestProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Available scope request properties. - :paramtype properties: ~azure.mgmt.reservations.models.AvailableScopeRequestProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class AvailableScopeRequestProperties(_serialization.Model): - """Available scope request properties. - - :ivar scopes: - :vartype scopes: list[str] - """ - - _attribute_map = { - "scopes": {"key": "scopes", "type": "[str]"}, - } - - def __init__(self, *, scopes: Optional[List[str]] = None, **kwargs: Any) -> None: - """ - :keyword scopes: - :paramtype scopes: list[str] - """ - super().__init__(**kwargs) - self.scopes = scopes - - -class BillingInformation(_serialization.Model): - """billing information. - - :ivar billing_currency_total_paid_amount: Pricing information containing the amount and the - currency code. - :vartype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price - :ivar billing_currency_prorated_amount: Pricing information containing the amount and the - currency code. - :vartype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price - :ivar billing_currency_remaining_commitment_amount: Pricing information containing the amount - and the currency code. - :vartype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price - """ - - _attribute_map = { - "billing_currency_total_paid_amount": {"key": "billingCurrencyTotalPaidAmount", "type": "Price"}, - "billing_currency_prorated_amount": {"key": "billingCurrencyProratedAmount", "type": "Price"}, - "billing_currency_remaining_commitment_amount": { - "key": "billingCurrencyRemainingCommitmentAmount", - "type": "Price", - }, - } - - def __init__( - self, - *, - billing_currency_total_paid_amount: Optional["_models.Price"] = None, - billing_currency_prorated_amount: Optional["_models.Price"] = None, - billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None, - **kwargs: Any - ) -> None: - """ - :keyword billing_currency_total_paid_amount: Pricing information containing the amount and the - currency code. - :paramtype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price - :keyword billing_currency_prorated_amount: Pricing information containing the amount and the - currency code. - :paramtype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price - :keyword billing_currency_remaining_commitment_amount: Pricing information containing the - amount and the currency code. - :paramtype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price - """ - super().__init__(**kwargs) - self.billing_currency_total_paid_amount = billing_currency_total_paid_amount - self.billing_currency_prorated_amount = billing_currency_prorated_amount - self.billing_currency_remaining_commitment_amount = billing_currency_remaining_commitment_amount - - -class CalculateExchangeOperationResultResponse(_serialization.Model): - """CalculateExchange operation result. - - :ivar id: It should match what is used to GET the operation result. - :vartype id: str - :ivar name: It must match the last segment of the id field, and will typically be a GUID / - system generated value. - :vartype name: str - :ivar status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", - and "Pending". - :vartype status: str or ~azure.mgmt.reservations.models.CalculateExchangeOperationResultStatus - :ivar properties: CalculateExchange response properties. - :vartype properties: ~azure.mgmt.reservations.models.CalculateExchangeResponseProperties - :ivar error: Required if status == failed or status == canceled. - :vartype error: ~azure.mgmt.reservations.models.OperationResultError - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "properties": {"key": "properties", "type": "CalculateExchangeResponseProperties"}, - "error": {"key": "error", "type": "OperationResultError"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - name: Optional[str] = None, - status: Optional[Union[str, "_models.CalculateExchangeOperationResultStatus"]] = None, - properties: Optional["_models.CalculateExchangeResponseProperties"] = None, - error: Optional["_models.OperationResultError"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: It should match what is used to GET the operation result. - :paramtype id: str - :keyword name: It must match the last segment of the id field, and will typically be a GUID / - system generated value. - :paramtype name: str - :keyword status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", - and "Pending". - :paramtype status: str or - ~azure.mgmt.reservations.models.CalculateExchangeOperationResultStatus - :keyword properties: CalculateExchange response properties. - :paramtype properties: ~azure.mgmt.reservations.models.CalculateExchangeResponseProperties - :keyword error: Required if status == failed or status == canceled. - :paramtype error: ~azure.mgmt.reservations.models.OperationResultError - """ - super().__init__(**kwargs) - self.id = id - self.name = name - self.status = status - self.properties = properties - self.error = error - - -class CalculateExchangeRequest(_serialization.Model): - """Calculate exchange request. - - :ivar properties: Calculate exchange request properties. - :vartype properties: ~azure.mgmt.reservations.models.CalculateExchangeRequestProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "CalculateExchangeRequestProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.CalculateExchangeRequestProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Calculate exchange request properties. - :paramtype properties: ~azure.mgmt.reservations.models.CalculateExchangeRequestProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class CalculateExchangeRequestProperties(_serialization.Model): - """Calculate exchange request properties. - - :ivar reservations_to_purchase: List of reservations that are being purchased in this exchange. - :vartype reservations_to_purchase: list[~azure.mgmt.reservations.models.PurchaseRequest] - :ivar savings_plans_to_purchase: List of savings plans that are being purchased in this - exchange. - :vartype savings_plans_to_purchase: - list[~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest] - :ivar reservations_to_exchange: List of reservations that are being returned in this exchange. - :vartype reservations_to_exchange: list[~azure.mgmt.reservations.models.ReservationToReturn] - """ - - _attribute_map = { - "reservations_to_purchase": {"key": "reservationsToPurchase", "type": "[PurchaseRequest]"}, - "savings_plans_to_purchase": {"key": "savingsPlansToPurchase", "type": "[SavingsPlanPurchaseRequest]"}, - "reservations_to_exchange": {"key": "reservationsToExchange", "type": "[ReservationToReturn]"}, - } - - def __init__( - self, - *, - reservations_to_purchase: Optional[List["_models.PurchaseRequest"]] = None, - savings_plans_to_purchase: Optional[List["_models.SavingsPlanPurchaseRequest"]] = None, - reservations_to_exchange: Optional[List["_models.ReservationToReturn"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reservations_to_purchase: List of reservations that are being purchased in this - exchange. - :paramtype reservations_to_purchase: list[~azure.mgmt.reservations.models.PurchaseRequest] - :keyword savings_plans_to_purchase: List of savings plans that are being purchased in this - exchange. - :paramtype savings_plans_to_purchase: - list[~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest] - :keyword reservations_to_exchange: List of reservations that are being returned in this - exchange. - :paramtype reservations_to_exchange: list[~azure.mgmt.reservations.models.ReservationToReturn] - """ - super().__init__(**kwargs) - self.reservations_to_purchase = reservations_to_purchase - self.savings_plans_to_purchase = savings_plans_to_purchase - self.reservations_to_exchange = reservations_to_exchange - - -class CalculateExchangeResponseProperties(_serialization.Model): - """CalculateExchange response properties. - - :ivar session_id: Exchange session identifier. - :vartype session_id: str - :ivar net_payable: Pricing information containing the amount and the currency code. - :vartype net_payable: ~azure.mgmt.reservations.models.Price - :ivar refunds_total: Pricing information containing the amount and the currency code. - :vartype refunds_total: ~azure.mgmt.reservations.models.Price - :ivar purchases_total: Pricing information containing the amount and the currency code. - :vartype purchases_total: ~azure.mgmt.reservations.models.Price - :ivar reservations_to_purchase: Details of the reservations being purchased. - :vartype reservations_to_purchase: - list[~azure.mgmt.reservations.models.ReservationToPurchaseCalculateExchange] - :ivar savings_plans_to_purchase: Details of the savings plans being purchased. - :vartype savings_plans_to_purchase: - list[~azure.mgmt.reservations.models.SavingsPlanToPurchaseCalculateExchange] - :ivar reservations_to_exchange: Details of the reservations being returned. - :vartype reservations_to_exchange: list[~azure.mgmt.reservations.models.ReservationToExchange] - :ivar policy_result: Exchange policy errors. - :vartype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors - """ - - _attribute_map = { - "session_id": {"key": "sessionId", "type": "str"}, - "net_payable": {"key": "netPayable", "type": "Price"}, - "refunds_total": {"key": "refundsTotal", "type": "Price"}, - "purchases_total": {"key": "purchasesTotal", "type": "Price"}, - "reservations_to_purchase": { - "key": "reservationsToPurchase", - "type": "[ReservationToPurchaseCalculateExchange]", - }, - "savings_plans_to_purchase": { - "key": "savingsPlansToPurchase", - "type": "[SavingsPlanToPurchaseCalculateExchange]", - }, - "reservations_to_exchange": {"key": "reservationsToExchange", "type": "[ReservationToExchange]"}, - "policy_result": {"key": "policyResult", "type": "ExchangePolicyErrors"}, - } - - def __init__( - self, - *, - session_id: Optional[str] = None, - net_payable: Optional["_models.Price"] = None, - refunds_total: Optional["_models.Price"] = None, - purchases_total: Optional["_models.Price"] = None, - reservations_to_purchase: Optional[List["_models.ReservationToPurchaseCalculateExchange"]] = None, - savings_plans_to_purchase: Optional[List["_models.SavingsPlanToPurchaseCalculateExchange"]] = None, - reservations_to_exchange: Optional[List["_models.ReservationToExchange"]] = None, - policy_result: Optional["_models.ExchangePolicyErrors"] = None, - **kwargs: Any - ) -> None: - """ - :keyword session_id: Exchange session identifier. - :paramtype session_id: str - :keyword net_payable: Pricing information containing the amount and the currency code. - :paramtype net_payable: ~azure.mgmt.reservations.models.Price - :keyword refunds_total: Pricing information containing the amount and the currency code. - :paramtype refunds_total: ~azure.mgmt.reservations.models.Price - :keyword purchases_total: Pricing information containing the amount and the currency code. - :paramtype purchases_total: ~azure.mgmt.reservations.models.Price - :keyword reservations_to_purchase: Details of the reservations being purchased. - :paramtype reservations_to_purchase: - list[~azure.mgmt.reservations.models.ReservationToPurchaseCalculateExchange] - :keyword savings_plans_to_purchase: Details of the savings plans being purchased. - :paramtype savings_plans_to_purchase: - list[~azure.mgmt.reservations.models.SavingsPlanToPurchaseCalculateExchange] - :keyword reservations_to_exchange: Details of the reservations being returned. - :paramtype reservations_to_exchange: - list[~azure.mgmt.reservations.models.ReservationToExchange] - :keyword policy_result: Exchange policy errors. - :paramtype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors - """ - super().__init__(**kwargs) - self.session_id = session_id - self.net_payable = net_payable - self.refunds_total = refunds_total - self.purchases_total = purchases_total - self.reservations_to_purchase = reservations_to_purchase - self.savings_plans_to_purchase = savings_plans_to_purchase - self.reservations_to_exchange = reservations_to_exchange - self.policy_result = policy_result - - -class CalculatePriceResponse(_serialization.Model): - """The response of calculate price for reservation. - - :ivar properties: Properties for calculate price response. - :vartype properties: ~azure.mgmt.reservations.models.CalculatePriceResponseProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "CalculatePriceResponseProperties"}, - } - - def __init__( - self, *, properties: Optional["_models.CalculatePriceResponseProperties"] = None, **kwargs: Any - ) -> None: - """ - :keyword properties: Properties for calculate price response. - :paramtype properties: ~azure.mgmt.reservations.models.CalculatePriceResponseProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class CalculatePriceResponseProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Properties for calculate price response. - - :ivar billing_currency_total: Currency and amount that customer will be charged in customer's - local currency. Tax is not included. - :vartype billing_currency_total: - ~azure.mgmt.reservations.models.CalculatePriceResponsePropertiesBillingCurrencyTotal - :ivar net_total: Net total amount in pricing currency. - :vartype net_total: float - :ivar tax_total: Tax amount in pricing currency. - :vartype tax_total: float - :ivar grand_total: Total amount in pricing currency. - :vartype grand_total: float - :ivar is_tax_included: Whether or not tax is included in grand total. - :vartype is_tax_included: bool - :ivar is_billing_partner_managed: True if billing is managed by Microsoft Partner. Used only - for CSP accounts. - :vartype is_billing_partner_managed: bool - :ivar reservation_order_id: GUID that represents reservation order that can be placed after - calculating price. - :vartype reservation_order_id: str - :ivar sku_title: Title of sku that is being purchased. - :vartype sku_title: str - :ivar sku_description: Description of sku that is being purchased. - :vartype sku_description: str - :ivar pricing_currency_total: Amount that Microsoft uses for record. Used during refund for - calculating refund limit. Tax is not included. - :vartype pricing_currency_total: - ~azure.mgmt.reservations.models.CalculatePriceResponsePropertiesPricingCurrencyTotal - :ivar payment_schedule: - :vartype payment_schedule: list[~azure.mgmt.reservations.models.PaymentDetail] - """ - - _attribute_map = { - "billing_currency_total": { - "key": "billingCurrencyTotal", - "type": "CalculatePriceResponsePropertiesBillingCurrencyTotal", - }, - "net_total": {"key": "netTotal", "type": "float"}, - "tax_total": {"key": "taxTotal", "type": "float"}, - "grand_total": {"key": "grandTotal", "type": "float"}, - "is_tax_included": {"key": "isTaxIncluded", "type": "bool"}, - "is_billing_partner_managed": {"key": "isBillingPartnerManaged", "type": "bool"}, - "reservation_order_id": {"key": "reservationOrderId", "type": "str"}, - "sku_title": {"key": "skuTitle", "type": "str"}, - "sku_description": {"key": "skuDescription", "type": "str"}, - "pricing_currency_total": { - "key": "pricingCurrencyTotal", - "type": "CalculatePriceResponsePropertiesPricingCurrencyTotal", - }, - "payment_schedule": {"key": "paymentSchedule", "type": "[PaymentDetail]"}, - } - - def __init__( - self, - *, - billing_currency_total: Optional["_models.CalculatePriceResponsePropertiesBillingCurrencyTotal"] = None, - net_total: Optional[float] = None, - tax_total: Optional[float] = None, - grand_total: Optional[float] = None, - is_tax_included: Optional[bool] = None, - is_billing_partner_managed: Optional[bool] = None, - reservation_order_id: Optional[str] = None, - sku_title: Optional[str] = None, - sku_description: Optional[str] = None, - pricing_currency_total: Optional["_models.CalculatePriceResponsePropertiesPricingCurrencyTotal"] = None, - payment_schedule: Optional[List["_models.PaymentDetail"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword billing_currency_total: Currency and amount that customer will be charged in - customer's local currency. Tax is not included. - :paramtype billing_currency_total: - ~azure.mgmt.reservations.models.CalculatePriceResponsePropertiesBillingCurrencyTotal - :keyword net_total: Net total amount in pricing currency. - :paramtype net_total: float - :keyword tax_total: Tax amount in pricing currency. - :paramtype tax_total: float - :keyword grand_total: Total amount in pricing currency. - :paramtype grand_total: float - :keyword is_tax_included: Whether or not tax is included in grand total. - :paramtype is_tax_included: bool - :keyword is_billing_partner_managed: True if billing is managed by Microsoft Partner. Used only - for CSP accounts. - :paramtype is_billing_partner_managed: bool - :keyword reservation_order_id: GUID that represents reservation order that can be placed after - calculating price. - :paramtype reservation_order_id: str - :keyword sku_title: Title of sku that is being purchased. - :paramtype sku_title: str - :keyword sku_description: Description of sku that is being purchased. - :paramtype sku_description: str - :keyword pricing_currency_total: Amount that Microsoft uses for record. Used during refund for - calculating refund limit. Tax is not included. - :paramtype pricing_currency_total: - ~azure.mgmt.reservations.models.CalculatePriceResponsePropertiesPricingCurrencyTotal - :keyword payment_schedule: - :paramtype payment_schedule: list[~azure.mgmt.reservations.models.PaymentDetail] - """ - super().__init__(**kwargs) - self.billing_currency_total = billing_currency_total - self.net_total = net_total - self.tax_total = tax_total - self.grand_total = grand_total - self.is_tax_included = is_tax_included - self.is_billing_partner_managed = is_billing_partner_managed - self.reservation_order_id = reservation_order_id - self.sku_title = sku_title - self.sku_description = sku_description - self.pricing_currency_total = pricing_currency_total - self.payment_schedule = payment_schedule - - -class CalculatePriceResponsePropertiesBillingCurrencyTotal(_serialization.Model): - """Currency and amount that customer will be charged in customer's local currency. Tax is not - included. - - :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase - record. - :vartype currency_code: str - :ivar amount: Amount in pricing currency. Tax is not included. - :vartype amount: float - """ - - _attribute_map = { - "currency_code": {"key": "currencyCode", "type": "str"}, - "amount": {"key": "amount", "type": "float"}, - } - - def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs: Any) -> None: - """ - :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this - purchase record. - :paramtype currency_code: str - :keyword amount: Amount in pricing currency. Tax is not included. - :paramtype amount: float - """ - super().__init__(**kwargs) - self.currency_code = currency_code - self.amount = amount - - -class CalculatePriceResponsePropertiesPricingCurrencyTotal(_serialization.Model): - """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is - not included. - - :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase - record. - :vartype currency_code: str - :ivar amount: - :vartype amount: float - """ - - _attribute_map = { - "currency_code": {"key": "currencyCode", "type": "str"}, - "amount": {"key": "amount", "type": "float"}, - } - - def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs: Any) -> None: - """ - :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this - purchase record. - :paramtype currency_code: str - :keyword amount: - :paramtype amount: float - """ - super().__init__(**kwargs) - self.currency_code = currency_code - self.amount = amount - - -class CalculateRefundRequest(_serialization.Model): - """Request containing information needed for calculating refund. - - :ivar id: Fully qualified identifier of the reservation order being returned. - :vartype id: str - :ivar properties: Properties needed for calculate refund including the scope and the - reservation to be returned. - :vartype properties: ~azure.mgmt.reservations.models.CalculateRefundRequestProperties - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "properties": {"key": "properties", "type": "CalculateRefundRequestProperties"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - properties: Optional["_models.CalculateRefundRequestProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Fully qualified identifier of the reservation order being returned. - :paramtype id: str - :keyword properties: Properties needed for calculate refund including the scope and the - reservation to be returned. - :paramtype properties: ~azure.mgmt.reservations.models.CalculateRefundRequestProperties - """ - super().__init__(**kwargs) - self.id = id - self.properties = properties - - -class CalculateRefundRequestProperties(_serialization.Model): - """Properties needed for calculate refund including the scope and the reservation to be returned. - - :ivar scope: The scope of the refund, e.g. Reservation. - :vartype scope: str - :ivar reservation_to_return: Reservation to return. - :vartype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn - """ - - _attribute_map = { - "scope": {"key": "scope", "type": "str"}, - "reservation_to_return": {"key": "reservationToReturn", "type": "ReservationToReturn"}, - } - - def __init__( - self, - *, - scope: Optional[str] = None, - reservation_to_return: Optional["_models.ReservationToReturn"] = None, - **kwargs: Any - ) -> None: - """ - :keyword scope: The scope of the refund, e.g. Reservation. - :paramtype scope: str - :keyword reservation_to_return: Reservation to return. - :paramtype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn - """ - super().__init__(**kwargs) - self.scope = scope - self.reservation_to_return = reservation_to_return - - -class CalculateRefundResponse(_serialization.Model): - """The response of calculate refund containing refund information of reservation. - - :ivar id: Fully qualified identifier of the reservation being returned. - :vartype id: str - :ivar properties: The refund properties of reservation. - :vartype properties: ~azure.mgmt.reservations.models.RefundResponseProperties - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "properties": {"key": "properties", "type": "RefundResponseProperties"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - properties: Optional["_models.RefundResponseProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Fully qualified identifier of the reservation being returned. - :paramtype id: str - :keyword properties: The refund properties of reservation. - :paramtype properties: ~azure.mgmt.reservations.models.RefundResponseProperties - """ - super().__init__(**kwargs) - self.id = id - self.properties = properties - - -class Catalog(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Product details of a type of resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar resource_type: The type of resource the sku applies to. - :vartype resource_type: str - :ivar name: The name of sku. - :vartype name: str - :ivar billing_plans: The billing plan options available for this sku. - :vartype billing_plans: dict[str, list[str or - ~azure.mgmt.reservations.models.ReservationBillingPlan]] - :ivar terms: Available reservation terms for this resource. - :vartype terms: list[str or ~azure.mgmt.reservations.models.ReservationTerm] - :ivar locations: - :vartype locations: list[str] - :ivar sku_properties: - :vartype sku_properties: list[~azure.mgmt.reservations.models.SkuProperty] - :ivar msrp: Pricing information about the sku. - :vartype msrp: ~azure.mgmt.reservations.models.CatalogMsrp - :ivar restrictions: - :vartype restrictions: list[~azure.mgmt.reservations.models.SkuRestriction] - :ivar tier: The tier of this sku. - :vartype tier: str - :ivar size: The size of this sku. - :vartype size: str - :ivar capabilities: - :vartype capabilities: list[~azure.mgmt.reservations.models.SkuCapability] - """ - - _validation = { - "resource_type": {"readonly": True}, - "name": {"readonly": True}, - "terms": {"readonly": True}, - "locations": {"readonly": True}, - "sku_properties": {"readonly": True}, - "msrp": {"readonly": True}, - "restrictions": {"readonly": True}, - "tier": {"readonly": True}, - "size": {"readonly": True}, - "capabilities": {"readonly": True}, - } - - _attribute_map = { - "resource_type": {"key": "resourceType", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "billing_plans": {"key": "billingPlans", "type": "{[str]}"}, - "terms": {"key": "terms", "type": "[str]"}, - "locations": {"key": "locations", "type": "[str]"}, - "sku_properties": {"key": "skuProperties", "type": "[SkuProperty]"}, - "msrp": {"key": "msrp", "type": "CatalogMsrp"}, - "restrictions": {"key": "restrictions", "type": "[SkuRestriction]"}, - "tier": {"key": "tier", "type": "str"}, - "size": {"key": "size", "type": "str"}, - "capabilities": {"key": "capabilities", "type": "[SkuCapability]"}, - } - - def __init__( - self, - *, - billing_plans: Optional[Dict[str, List[Union[str, "_models.ReservationBillingPlan"]]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword billing_plans: The billing plan options available for this sku. - :paramtype billing_plans: dict[str, list[str or - ~azure.mgmt.reservations.models.ReservationBillingPlan]] - """ - super().__init__(**kwargs) - self.resource_type = None - self.name = None - self.billing_plans = billing_plans - self.terms = None - self.locations = None - self.sku_properties = None - self.msrp = None - self.restrictions = None - self.tier = None - self.size = None - self.capabilities = None - - -class CatalogMsrp(_serialization.Model): - """Pricing information about the sku. - - :ivar p1_y: Amount in pricing currency. Tax not included. - :vartype p1_y: ~azure.mgmt.reservations.models.Price - :ivar p3_y: Amount in pricing currency. Tax not included. - :vartype p3_y: ~azure.mgmt.reservations.models.Price - :ivar p5_y: Amount in pricing currency. Tax not included. - :vartype p5_y: ~azure.mgmt.reservations.models.Price - """ - - _attribute_map = { - "p1_y": {"key": "p1Y", "type": "Price"}, - "p3_y": {"key": "p3Y", "type": "Price"}, - "p5_y": {"key": "p5Y", "type": "Price"}, - } - - def __init__( - self, - *, - p1_y: Optional["_models.Price"] = None, - p3_y: Optional["_models.Price"] = None, - p5_y: Optional["_models.Price"] = None, - **kwargs: Any - ) -> None: - """ - :keyword p1_y: Amount in pricing currency. Tax not included. - :paramtype p1_y: ~azure.mgmt.reservations.models.Price - :keyword p3_y: Amount in pricing currency. Tax not included. - :paramtype p3_y: ~azure.mgmt.reservations.models.Price - :keyword p5_y: Amount in pricing currency. Tax not included. - :paramtype p5_y: ~azure.mgmt.reservations.models.Price - """ - super().__init__(**kwargs) - self.p1_y = p1_y - self.p3_y = p3_y - self.p5_y = p5_y - - -class CatalogsResult(_serialization.Model): - """The list of catalogs and pagination information. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of catalogs. - :vartype value: list[~azure.mgmt.reservations.models.Catalog] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - :ivar total_items: The total amount of catalog items. - :vartype total_items: int - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Catalog]"}, - "next_link": {"key": "nextLink", "type": "str"}, - "total_items": {"key": "totalItems", "type": "int"}, - } - - def __init__(self, *, total_items: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword total_items: The total amount of catalog items. - :paramtype total_items: int - """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - self.total_items = total_items - - -class ChangeDirectoryRequest(_serialization.Model): - """Request body for change directory of a reservation. - - :ivar destination_tenant_id: Tenant id GUID that reservation order is to be transferred to. - :vartype destination_tenant_id: str - """ - - _attribute_map = { - "destination_tenant_id": {"key": "destinationTenantId", "type": "str"}, - } - - def __init__(self, *, destination_tenant_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword destination_tenant_id: Tenant id GUID that reservation order is to be transferred to. - :paramtype destination_tenant_id: str - """ - super().__init__(**kwargs) - self.destination_tenant_id = destination_tenant_id - - -class ChangeDirectoryResponse(_serialization.Model): - """Change directory response. - - :ivar reservation_order: Change directory result for reservation order or reservation. - :vartype reservation_order: ~azure.mgmt.reservations.models.ChangeDirectoryResult - :ivar reservations: - :vartype reservations: list[~azure.mgmt.reservations.models.ChangeDirectoryResult] - """ - - _attribute_map = { - "reservation_order": {"key": "reservationOrder", "type": "ChangeDirectoryResult"}, - "reservations": {"key": "reservations", "type": "[ChangeDirectoryResult]"}, - } - - def __init__( - self, - *, - reservation_order: Optional["_models.ChangeDirectoryResult"] = None, - reservations: Optional[List["_models.ChangeDirectoryResult"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reservation_order: Change directory result for reservation order or reservation. - :paramtype reservation_order: ~azure.mgmt.reservations.models.ChangeDirectoryResult - :keyword reservations: - :paramtype reservations: list[~azure.mgmt.reservations.models.ChangeDirectoryResult] - """ - super().__init__(**kwargs) - self.reservation_order = reservation_order - self.reservations = reservations - - -class ChangeDirectoryResult(_serialization.Model): - """Change directory result for reservation order or reservation. - - :ivar id: Identifier of the reservation order or reservation. - :vartype id: str - :ivar name: Name of the reservation order or reservation. - :vartype name: str - :ivar is_succeeded: True if change directory operation succeeded on this reservation order or - reservation. - :vartype is_succeeded: bool - :ivar error: Error reason if operation failed. Null otherwise. - :vartype error: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "is_succeeded": {"key": "isSucceeded", "type": "bool"}, - "error": {"key": "error", "type": "str"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - name: Optional[str] = None, - is_succeeded: Optional[bool] = None, - error: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Identifier of the reservation order or reservation. - :paramtype id: str - :keyword name: Name of the reservation order or reservation. - :paramtype name: str - :keyword is_succeeded: True if change directory operation succeeded on this reservation order - or reservation. - :paramtype is_succeeded: bool - :keyword error: Error reason if operation failed. Null otherwise. - :paramtype error: str - """ - super().__init__(**kwargs) - self.id = id - self.name = name - self.is_succeeded = is_succeeded - self.error = error - - -class Price(_serialization.Model): - """Pricing information containing the amount and the currency code. - - :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase - record. - :vartype currency_code: str - :ivar amount: - :vartype amount: float - """ - - _attribute_map = { - "currency_code": {"key": "currencyCode", "type": "str"}, - "amount": {"key": "amount", "type": "float"}, - } - - def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs: Any) -> None: - """ - :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this - purchase record. - :paramtype currency_code: str - :keyword amount: - :paramtype amount: float - """ - super().__init__(**kwargs) - self.currency_code = currency_code - self.amount = amount - - -class Commitment(Price): - """Commitment towards the benefit. - - :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase - record. - :vartype currency_code: str - :ivar amount: - :vartype amount: float - :ivar grain: Commitment grain. "Hourly" - :vartype grain: str or ~azure.mgmt.reservations.models.CommitmentGrain - """ - - _attribute_map = { - "currency_code": {"key": "currencyCode", "type": "str"}, - "amount": {"key": "amount", "type": "float"}, - "grain": {"key": "grain", "type": "str"}, - } - - def __init__( - self, - *, - currency_code: Optional[str] = None, - amount: Optional[float] = None, - grain: Optional[Union[str, "_models.CommitmentGrain"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this - purchase record. - :paramtype currency_code: str - :keyword amount: - :paramtype amount: float - :keyword grain: Commitment grain. "Hourly" - :paramtype grain: str or ~azure.mgmt.reservations.models.CommitmentGrain - """ - super().__init__(currency_code=currency_code, amount=amount, **kwargs) - self.grain = grain - - -class CreateGenericQuotaRequestParameters(_serialization.Model): - """Quota change requests information. - - :ivar value: Quota change requests. - :vartype value: list[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[CurrentQuotaLimitBase]"}, - } - - def __init__(self, *, value: Optional[List["_models.CurrentQuotaLimitBase"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Quota change requests. - :paramtype value: list[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] - """ - super().__init__(**kwargs) - self.value = value - - -class CurrentQuotaLimit(_serialization.Model): - """Current quota limits. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provisioning_state: The details of the quota request status. Known values are: - "Accepted", "Invalid", "Succeeded", "Failed", and "InProgress". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :ivar message: A user friendly message. - :vartype message: str - :ivar id: The quota request ID. - :vartype id: str - :ivar name: The name of the quota request. - :vartype name: str - :ivar type: Type of resource. "Microsoft.Capacity/ServiceLimits". - :vartype type: str - :ivar properties: Quota properties for the resource. - :vartype properties: ~azure.mgmt.reservations.models.QuotaProperties - """ - - _validation = { - "provisioning_state": {"readonly": True}, - "message": {"readonly": True}, - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "message": {"key": "properties.message", "type": "str"}, - "id": {"key": "quotaInformation.id", "type": "str"}, - "name": {"key": "quotaInformation.name", "type": "str"}, - "type": {"key": "quotaInformation.type", "type": "str"}, - "properties": {"key": "quotaInformation.properties", "type": "QuotaProperties"}, - } - - def __init__(self, *, properties: Optional["_models.QuotaProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Quota properties for the resource. - :paramtype properties: ~azure.mgmt.reservations.models.QuotaProperties - """ - super().__init__(**kwargs) - self.provisioning_state = None - self.message = None - self.id = None - self.name = None - self.type = None - self.properties = properties - - -class CurrentQuotaLimitBase(_serialization.Model): - """Quota properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The quota request ID. - :vartype id: str - :ivar name: The name of the quota request. - :vartype name: str - :ivar type: Type of resource. "Microsoft.Capacity/ServiceLimits". - :vartype type: str - :ivar properties: Quota properties for the resource. - :vartype properties: ~azure.mgmt.reservations.models.QuotaProperties - """ - - _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"}, - "properties": {"key": "properties", "type": "QuotaProperties"}, - } - - def __init__(self, *, properties: Optional["_models.QuotaProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Quota properties for the resource. - :paramtype properties: ~azure.mgmt.reservations.models.QuotaProperties - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.properties = properties - - -class Error(_serialization.Model): - """Error information. - - :ivar error: Extended error information including error code and error message. - :vartype error: ~azure.mgmt.reservations.models.ExtendedErrorInfo - """ - - _attribute_map = { - "error": {"key": "error", "type": "ExtendedErrorInfo"}, - } - - def __init__(self, *, error: Optional["_models.ExtendedErrorInfo"] = None, **kwargs: Any) -> None: - """ - :keyword error: Extended error information including error code and error message. - :paramtype error: ~azure.mgmt.reservations.models.ExtendedErrorInfo - """ - super().__init__(**kwargs) - self.error = error - - -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 - :ivar target: The target of the particular error. - :vartype target: str - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - self.target = 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. - - :ivar error: The details of the error. - :vartype error: ~azure.mgmt.reservations.models.ErrorDetails - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetails"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs: Any) -> None: - """ - :keyword error: The details of the error. - :paramtype error: ~azure.mgmt.reservations.models.ErrorDetails - """ - super().__init__(**kwargs) - self.error = error - - -class ExceptionResponse(_serialization.Model): - """The API error. - - :ivar error: The API error details. - :vartype error: ~azure.mgmt.reservations.models.ServiceError - """ - - _attribute_map = { - "error": {"key": "error", "type": "ServiceError"}, - } - - def __init__(self, *, error: Optional["_models.ServiceError"] = None, **kwargs: Any) -> None: - """ - :keyword error: The API error details. - :paramtype error: ~azure.mgmt.reservations.models.ServiceError - """ - super().__init__(**kwargs) - self.error = error - - -class ExchangeOperationResultResponse(_serialization.Model): - """Exchange operation result. - - :ivar id: It should match what is used to GET the operation result. - :vartype id: str - :ivar name: It must match the last segment of the id field, and will typically be a GUID / - system generated value. - :vartype name: str - :ivar status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", - "PendingRefunds", and "PendingPurchases". - :vartype status: str or ~azure.mgmt.reservations.models.ExchangeOperationResultStatus - :ivar properties: Exchange response properties. - :vartype properties: ~azure.mgmt.reservations.models.ExchangeResponseProperties - :ivar error: Required if status == failed or status == canceled. - :vartype error: ~azure.mgmt.reservations.models.OperationResultError - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "properties": {"key": "properties", "type": "ExchangeResponseProperties"}, - "error": {"key": "error", "type": "OperationResultError"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - name: Optional[str] = None, - status: Optional[Union[str, "_models.ExchangeOperationResultStatus"]] = None, - properties: Optional["_models.ExchangeResponseProperties"] = None, - error: Optional["_models.OperationResultError"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: It should match what is used to GET the operation result. - :paramtype id: str - :keyword name: It must match the last segment of the id field, and will typically be a GUID / - system generated value. - :paramtype name: str - :keyword status: Status of the operation. Known values are: "Succeeded", "Failed", "Cancelled", - "PendingRefunds", and "PendingPurchases". - :paramtype status: str or ~azure.mgmt.reservations.models.ExchangeOperationResultStatus - :keyword properties: Exchange response properties. - :paramtype properties: ~azure.mgmt.reservations.models.ExchangeResponseProperties - :keyword error: Required if status == failed or status == canceled. - :paramtype error: ~azure.mgmt.reservations.models.OperationResultError - """ - super().__init__(**kwargs) - self.id = id - self.name = name - self.status = status - self.properties = properties - self.error = error - - -class ExchangePolicyError(_serialization.Model): - """error details. - - :ivar code: - :vartype code: str - :ivar message: - :vartype message: str - """ - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword code: - :paramtype code: str - :keyword message: - :paramtype message: str - """ - super().__init__(**kwargs) - self.code = code - self.message = message - - -class ExchangePolicyErrors(_serialization.Model): - """Exchange policy errors. - - :ivar policy_errors: Exchange Policy errors. - :vartype policy_errors: list[~azure.mgmt.reservations.models.ExchangePolicyError] - """ - - _attribute_map = { - "policy_errors": {"key": "policyErrors", "type": "[ExchangePolicyError]"}, - } - - def __init__(self, *, policy_errors: Optional[List["_models.ExchangePolicyError"]] = None, **kwargs: Any) -> None: - """ - :keyword policy_errors: Exchange Policy errors. - :paramtype policy_errors: list[~azure.mgmt.reservations.models.ExchangePolicyError] - """ - super().__init__(**kwargs) - self.policy_errors = policy_errors - - -class ExchangeRequest(_serialization.Model): - """Exchange request. - - :ivar properties: Exchange request properties. - :vartype properties: ~azure.mgmt.reservations.models.ExchangeRequestProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "ExchangeRequestProperties"}, - } - - def __init__(self, *, properties: Optional["_models.ExchangeRequestProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Exchange request properties. - :paramtype properties: ~azure.mgmt.reservations.models.ExchangeRequestProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class ExchangeRequestProperties(_serialization.Model): - """Exchange request properties. - - :ivar session_id: SessionId that was returned by CalculateExchange API. - :vartype session_id: str - """ - - _attribute_map = { - "session_id": {"key": "sessionId", "type": "str"}, - } - - def __init__(self, *, session_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword session_id: SessionId that was returned by CalculateExchange API. - :paramtype session_id: str - """ - super().__init__(**kwargs) - self.session_id = session_id - - -class ExchangeResponseProperties(_serialization.Model): - """Exchange response properties. - - :ivar session_id: Exchange session identifier. - :vartype session_id: str - :ivar net_payable: Pricing information containing the amount and the currency code. - :vartype net_payable: ~azure.mgmt.reservations.models.Price - :ivar refunds_total: Pricing information containing the amount and the currency code. - :vartype refunds_total: ~azure.mgmt.reservations.models.Price - :ivar purchases_total: Pricing information containing the amount and the currency code. - :vartype purchases_total: ~azure.mgmt.reservations.models.Price - :ivar reservations_to_purchase: Details of the reservations being purchased. - :vartype reservations_to_purchase: - list[~azure.mgmt.reservations.models.ReservationToPurchaseExchange] - :ivar savings_plans_to_purchase: Details of the savings plans being purchased. - :vartype savings_plans_to_purchase: - list[~azure.mgmt.reservations.models.SavingsPlanToPurchaseExchange] - :ivar reservations_to_exchange: Details of the reservations being returned. - :vartype reservations_to_exchange: - list[~azure.mgmt.reservations.models.ReservationToReturnForExchange] - :ivar policy_result: Exchange policy errors. - :vartype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors - """ - - _attribute_map = { - "session_id": {"key": "sessionId", "type": "str"}, - "net_payable": {"key": "netPayable", "type": "Price"}, - "refunds_total": {"key": "refundsTotal", "type": "Price"}, - "purchases_total": {"key": "purchasesTotal", "type": "Price"}, - "reservations_to_purchase": {"key": "reservationsToPurchase", "type": "[ReservationToPurchaseExchange]"}, - "savings_plans_to_purchase": {"key": "savingsPlansToPurchase", "type": "[SavingsPlanToPurchaseExchange]"}, - "reservations_to_exchange": {"key": "reservationsToExchange", "type": "[ReservationToReturnForExchange]"}, - "policy_result": {"key": "policyResult", "type": "ExchangePolicyErrors"}, - } - - def __init__( - self, - *, - session_id: Optional[str] = None, - net_payable: Optional["_models.Price"] = None, - refunds_total: Optional["_models.Price"] = None, - purchases_total: Optional["_models.Price"] = None, - reservations_to_purchase: Optional[List["_models.ReservationToPurchaseExchange"]] = None, - savings_plans_to_purchase: Optional[List["_models.SavingsPlanToPurchaseExchange"]] = None, - reservations_to_exchange: Optional[List["_models.ReservationToReturnForExchange"]] = None, - policy_result: Optional["_models.ExchangePolicyErrors"] = None, - **kwargs: Any - ) -> None: - """ - :keyword session_id: Exchange session identifier. - :paramtype session_id: str - :keyword net_payable: Pricing information containing the amount and the currency code. - :paramtype net_payable: ~azure.mgmt.reservations.models.Price - :keyword refunds_total: Pricing information containing the amount and the currency code. - :paramtype refunds_total: ~azure.mgmt.reservations.models.Price - :keyword purchases_total: Pricing information containing the amount and the currency code. - :paramtype purchases_total: ~azure.mgmt.reservations.models.Price - :keyword reservations_to_purchase: Details of the reservations being purchased. - :paramtype reservations_to_purchase: - list[~azure.mgmt.reservations.models.ReservationToPurchaseExchange] - :keyword savings_plans_to_purchase: Details of the savings plans being purchased. - :paramtype savings_plans_to_purchase: - list[~azure.mgmt.reservations.models.SavingsPlanToPurchaseExchange] - :keyword reservations_to_exchange: Details of the reservations being returned. - :paramtype reservations_to_exchange: - list[~azure.mgmt.reservations.models.ReservationToReturnForExchange] - :keyword policy_result: Exchange policy errors. - :paramtype policy_result: ~azure.mgmt.reservations.models.ExchangePolicyErrors - """ - super().__init__(**kwargs) - self.session_id = session_id - self.net_payable = net_payable - self.refunds_total = refunds_total - self.purchases_total = purchases_total - self.reservations_to_purchase = reservations_to_purchase - self.savings_plans_to_purchase = savings_plans_to_purchase - self.reservations_to_exchange = reservations_to_exchange - self.policy_result = policy_result - - -class ExtendedErrorInfo(_serialization.Model): - """Extended error information including error code and error message. - - :ivar code: Error code describing the reason that service is not able to process the incoming - request. Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", - "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", - "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", - "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", - "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", - "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", - "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", - "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", - "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", - "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", - "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", - "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", - "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", - "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", - "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", - "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", - "BillingTransientError", "BillingError", "FulfillmentConfigurationError", - "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", - "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and - "RefundLimitExceeded". - :vartype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode - :ivar message: - :vartype message: str - """ - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__( - self, - *, - code: Optional[Union[str, "_models.ErrorResponseCode"]] = None, - message: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword code: Error code describing the reason that service is not able to process the - incoming request. Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", - "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", - "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", - "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", - "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", - "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", - "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", - "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", - "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", - "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", - "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", - "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", - "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", - "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", - "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", - "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", - "BillingTransientError", "BillingError", "FulfillmentConfigurationError", - "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", - "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and - "RefundLimitExceeded". - :paramtype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode - :keyword message: - :paramtype message: str - """ - super().__init__(**kwargs) - self.code = code - self.message = message - - -class ExtendedStatusInfo(_serialization.Model): - """ExtendedStatusInfo. - - :ivar status_code: Known values are: "None", "Pending", "Processing", "Active", - "PurchaseError", "PaymentInstrumentError", "Split", "Merged", "Expired", and "Succeeded". - :vartype status_code: str or ~azure.mgmt.reservations.models.ReservationStatusCode - :ivar message: The message giving detailed information about the status code. - :vartype message: str - """ - - _attribute_map = { - "status_code": {"key": "statusCode", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__( - self, - *, - status_code: Optional[Union[str, "_models.ReservationStatusCode"]] = None, - message: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword status_code: Known values are: "None", "Pending", "Processing", "Active", - "PurchaseError", "PaymentInstrumentError", "Split", "Merged", "Expired", and "Succeeded". - :paramtype status_code: str or ~azure.mgmt.reservations.models.ReservationStatusCode - :keyword message: The message giving detailed information about the status code. - :paramtype message: str - """ - super().__init__(**kwargs) - self.status_code = status_code - self.message = message - - -class MergeRequest(_serialization.Model): - """The request for reservation merge. - - :ivar sources: Format of the resource id should be - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype sources: list[str] - """ - - _attribute_map = { - "sources": {"key": "properties.sources", "type": "[str]"}, - } - - def __init__(self, *, sources: Optional[List[str]] = None, **kwargs: Any) -> None: - """ - :keyword sources: Format of the resource id should be - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype sources: list[str] - """ - super().__init__(**kwargs) - self.sources = sources - - -class OperationDisplay(_serialization.Model): - """Information about an operation. - - :ivar provider: - :vartype provider: str - :ivar resource: - :vartype resource: str - :ivar operation: - :vartype operation: str - :ivar description: - :vartype description: str - """ - - _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, - *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - description: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: - :paramtype provider: str - :keyword resource: - :paramtype resource: str - :keyword operation: - :paramtype operation: str - :keyword description: - :paramtype description: str - """ - super().__init__(**kwargs) - self.provider = provider - self.resource = resource - self.operation = operation - self.description = description - - -class OperationList(_serialization.Model): - """Paginated list of operations. - - :ivar value: - :vartype value: list[~azure.mgmt.reservations.models.OperationResponse] - :ivar next_link: Url to get the next page of items. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[OperationResponse]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.OperationResponse"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: - :paramtype value: list[~azure.mgmt.reservations.models.OperationResponse] - :keyword next_link: Url to get the next page of items. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class OperationResponse(_serialization.Model): - """The response containing operation information. - - :ivar name: Name of the operation. - :vartype name: str - :ivar is_data_action: Indicates whether the operation is a data action. - :vartype is_data_action: bool - :ivar display: Display of the operation. - :vartype display: ~azure.mgmt.reservations.models.OperationDisplay - :ivar origin: Origin of the operation. - :vartype origin: str - :ivar properties: Properties of the operation. - :vartype properties: JSON - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "is_data_action": {"key": "isDataAction", "type": "bool"}, - "display": {"key": "display", "type": "OperationDisplay"}, - "origin": {"key": "origin", "type": "str"}, - "properties": {"key": "properties", "type": "object"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - is_data_action: Optional[bool] = None, - display: Optional["_models.OperationDisplay"] = None, - origin: Optional[str] = None, - properties: Optional[JSON] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Name of the operation. - :paramtype name: str - :keyword is_data_action: Indicates whether the operation is a data action. - :paramtype is_data_action: bool - :keyword display: Display of the operation. - :paramtype display: ~azure.mgmt.reservations.models.OperationDisplay - :keyword origin: Origin of the operation. - :paramtype origin: str - :keyword properties: Properties of the operation. - :paramtype properties: JSON - """ - super().__init__(**kwargs) - self.name = name - self.is_data_action = is_data_action - self.display = display - self.origin = origin - self.properties = properties - - -class OperationResultError(_serialization.Model): - """Required if status == failed or status == canceled. - - :ivar code: Required if status == failed or status == cancelled. If status == failed, provide - an invariant error code used for error troubleshooting, aggregation, and analysis. - :vartype code: str - :ivar message: Required if status == failed. Localized. If status == failed, provide an - actionable error message indicating what error occurred, and what the user can do to address - the issue. - :vartype message: str - """ - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword code: Required if status == failed or status == cancelled. If status == failed, - provide an invariant error code used for error troubleshooting, aggregation, and analysis. - :paramtype code: str - :keyword message: Required if status == failed. Localized. If status == failed, provide an - actionable error message indicating what error occurred, and what the user can do to address - the issue. - :paramtype message: str - """ - super().__init__(**kwargs) - self.code = code - self.message = message - - -class Patch(_serialization.Model): - """The request for reservation patch. - - :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and - "ManagementGroup". - :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :ivar applied_scopes: List of the subscriptions that the benefit will be applied. Do not - specify if AppliedScopeType is Shared. This property will be deprecated and replaced by - appliedScopeProperties instead for Single AppliedScopeType. - :vartype applied_scopes: list[str] - :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not - applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is - ManagementGroup. - :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in - the same VM size group. Only specify for VirtualMachines reserved resource type. Known values - are: "On" and "Off". - :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility - :ivar name: Display name of the reservation. - :vartype name: str - :ivar renew: Setting this to true will automatically purchase a new reservation on the - expiration date time. - :vartype renew: bool - :ivar renew_properties: - :vartype renew_properties: ~azure.mgmt.reservations.models.PatchPropertiesRenewProperties - :ivar review_date_time: This is the date-time when the Azure hybrid benefit needs to be - reviewed. - :vartype review_date_time: ~datetime.datetime - """ - - _attribute_map = { - "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, - "applied_scopes": {"key": "properties.appliedScopes", "type": "[str]"}, - "applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"}, - "instance_flexibility": {"key": "properties.instanceFlexibility", "type": "str"}, - "name": {"key": "properties.name", "type": "str"}, - "renew": {"key": "properties.renew", "type": "bool"}, - "renew_properties": {"key": "properties.renewProperties", "type": "PatchPropertiesRenewProperties"}, - "review_date_time": {"key": "properties.reviewDateTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, - applied_scopes: Optional[List[str]] = None, - applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, - instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, - name: Optional[str] = None, - renew: bool = False, - renew_properties: Optional["_models.PatchPropertiesRenewProperties"] = None, - review_date_time: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", - and "ManagementGroup". - :paramtype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :keyword applied_scopes: List of the subscriptions that the benefit will be applied. Do not - specify if AppliedScopeType is Shared. This property will be deprecated and replaced by - appliedScopeProperties instead for Single AppliedScopeType. - :paramtype applied_scopes: list[str] - :keyword applied_scope_properties: Properties specific to applied scope type. Not required if - not applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType - is ManagementGroup. - :paramtype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs - in the same VM size group. Only specify for VirtualMachines reserved resource type. Known - values are: "On" and "Off". - :paramtype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility - :keyword name: Display name of the reservation. - :paramtype name: str - :keyword renew: Setting this to true will automatically purchase a new reservation on the - expiration date time. - :paramtype renew: bool - :keyword renew_properties: - :paramtype renew_properties: ~azure.mgmt.reservations.models.PatchPropertiesRenewProperties - :keyword review_date_time: This is the date-time when the Azure hybrid benefit needs to be - reviewed. - :paramtype review_date_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.applied_scope_type = applied_scope_type - self.applied_scopes = applied_scopes - self.applied_scope_properties = applied_scope_properties - self.instance_flexibility = instance_flexibility - self.name = name - self.renew = renew - self.renew_properties = renew_properties - self.review_date_time = review_date_time - - -class PatchPropertiesRenewProperties(_serialization.Model): - """PatchPropertiesRenewProperties. - - :ivar purchase_properties: The request for reservation purchase. - :vartype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest - """ - - _attribute_map = { - "purchase_properties": {"key": "purchaseProperties", "type": "PurchaseRequest"}, - } - - def __init__(self, *, purchase_properties: Optional["_models.PurchaseRequest"] = None, **kwargs: Any) -> None: - """ - :keyword purchase_properties: The request for reservation purchase. - :paramtype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest - """ - super().__init__(**kwargs) - self.purchase_properties = purchase_properties - - -class PaymentDetail(_serialization.Model): - """Information about payment related to a reservation order. - - :ivar due_date: Date when the payment needs to be done. - :vartype due_date: ~datetime.date - :ivar payment_date: Date when the transaction is completed. Is null when it is scheduled. - :vartype payment_date: ~datetime.date - :ivar pricing_currency_total: Amount in pricing currency. Tax not included. - :vartype pricing_currency_total: ~azure.mgmt.reservations.models.Price - :ivar billing_currency_total: Amount charged in Billing currency. Tax not included. Is null for - future payments. - :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price - :ivar billing_account: Shows the Account that is charged for this payment. - :vartype billing_account: str - :ivar status: Describes whether the payment is completed, failed, cancelled or scheduled in the - future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled". - :vartype status: str or ~azure.mgmt.reservations.models.PaymentStatus - :ivar extended_status_info: - :vartype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo - """ - - _attribute_map = { - "due_date": {"key": "dueDate", "type": "date"}, - "payment_date": {"key": "paymentDate", "type": "date"}, - "pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"}, - "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, - "billing_account": {"key": "billingAccount", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "extended_status_info": {"key": "extendedStatusInfo", "type": "ExtendedStatusInfo"}, - } - - def __init__( - self, - *, - due_date: Optional[datetime.date] = None, - payment_date: Optional[datetime.date] = None, - pricing_currency_total: Optional["_models.Price"] = None, - billing_currency_total: Optional["_models.Price"] = None, - billing_account: Optional[str] = None, - status: Optional[Union[str, "_models.PaymentStatus"]] = None, - extended_status_info: Optional["_models.ExtendedStatusInfo"] = None, - **kwargs: Any - ) -> None: - """ - :keyword due_date: Date when the payment needs to be done. - :paramtype due_date: ~datetime.date - :keyword payment_date: Date when the transaction is completed. Is null when it is scheduled. - :paramtype payment_date: ~datetime.date - :keyword pricing_currency_total: Amount in pricing currency. Tax not included. - :paramtype pricing_currency_total: ~azure.mgmt.reservations.models.Price - :keyword billing_currency_total: Amount charged in Billing currency. Tax not included. Is null - for future payments. - :paramtype billing_currency_total: ~azure.mgmt.reservations.models.Price - :keyword billing_account: Shows the Account that is charged for this payment. - :paramtype billing_account: str - :keyword status: Describes whether the payment is completed, failed, cancelled or scheduled in - the future. Known values are: "Succeeded", "Failed", "Scheduled", and "Cancelled". - :paramtype status: str or ~azure.mgmt.reservations.models.PaymentStatus - :keyword extended_status_info: - :paramtype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo - """ - super().__init__(**kwargs) - self.due_date = due_date - self.payment_date = payment_date - self.pricing_currency_total = pricing_currency_total - self.billing_currency_total = billing_currency_total - self.billing_account = billing_account - self.status = status - self.extended_status_info = extended_status_info - - -class Resource(_serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/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.reservations.models.SystemData - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.system_data = None - - -class ProxyResource(Resource): - """The resource model definition for a Azure Resource Manager proxy resource. It will not have - tags and a location. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/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.reservations.models.SystemData - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - - -class PurchaseRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes - """The request for reservation purchase. - - :ivar sku: The name of sku. - :vartype sku: ~azure.mgmt.reservations.models.SkuName - :ivar location: The Azure region where the reserved resource lives. - :vartype location: str - :ivar reserved_resource_type: The type of the resource that is being reserved. Known values - are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", - "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", - "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", - "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", - "SqlEdge", and "VirtualMachineSoftware". - :vartype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType - :ivar billing_scope_id: Subscription that will be charged for purchasing reservation or savings - plan. - :vartype billing_scope_id: str - :ivar term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". - :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". - :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :ivar quantity: Quantity of the skus that are part of the reservation. - :vartype quantity: int - :ivar display_name: Friendly name of the reservation. - :vartype display_name: str - :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and - "ManagementGroup". - :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :ivar applied_scopes: List of the subscriptions that the benefit will be applied. Do not - specify if AppliedScopeType is Shared. This property will be deprecated and replaced by - appliedScopeProperties instead for Single AppliedScopeType. - :vartype applied_scopes: list[str] - :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not - applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is - ManagementGroup. - :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :ivar renew: Setting this to true will automatically purchase a new reservation on the - expiration date time. - :vartype renew: bool - :ivar reserved_resource_properties: Properties specific to each reserved resource type. Not - required if not applicable. - :vartype reserved_resource_properties: - ~azure.mgmt.reservations.models.PurchaseRequestPropertiesReservedResourceProperties - :ivar review_date_time: This is the date-time when the Azure hybrid benefit needs to be - reviewed. - :vartype review_date_time: ~datetime.datetime - """ - - _attribute_map = { - "sku": {"key": "sku", "type": "SkuName"}, - "location": {"key": "location", "type": "str"}, - "reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"}, - "billing_scope_id": {"key": "properties.billingScopeId", "type": "str"}, - "term": {"key": "properties.term", "type": "str"}, - "billing_plan": {"key": "properties.billingPlan", "type": "str"}, - "quantity": {"key": "properties.quantity", "type": "int"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, - "applied_scopes": {"key": "properties.appliedScopes", "type": "[str]"}, - "applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"}, - "renew": {"key": "properties.renew", "type": "bool"}, - "reserved_resource_properties": { - "key": "properties.reservedResourceProperties", - "type": "PurchaseRequestPropertiesReservedResourceProperties", - }, - "review_date_time": {"key": "properties.reviewDateTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - sku: Optional["_models.SkuName"] = None, - location: Optional[str] = None, - reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None, - billing_scope_id: Optional[str] = None, - term: Optional[Union[str, "_models.ReservationTerm"]] = None, - billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, - quantity: Optional[int] = None, - display_name: Optional[str] = None, - applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, - applied_scopes: Optional[List[str]] = None, - applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, - renew: bool = False, - reserved_resource_properties: Optional["_models.PurchaseRequestPropertiesReservedResourceProperties"] = None, - review_date_time: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword sku: The name of sku. - :paramtype sku: ~azure.mgmt.reservations.models.SkuName - :keyword location: The Azure region where the reserved resource lives. - :paramtype location: str - :keyword reserved_resource_type: The type of the resource that is being reserved. Known values - are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", - "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", - "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", - "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", - "SqlEdge", and "VirtualMachineSoftware". - :paramtype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType - :keyword billing_scope_id: Subscription that will be charged for purchasing reservation or - savings plan. - :paramtype billing_scope_id: str - :keyword term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". - :paramtype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :keyword billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". - :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :keyword quantity: Quantity of the skus that are part of the reservation. - :paramtype quantity: int - :keyword display_name: Friendly name of the reservation. - :paramtype display_name: str - :keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", - and "ManagementGroup". - :paramtype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :keyword applied_scopes: List of the subscriptions that the benefit will be applied. Do not - specify if AppliedScopeType is Shared. This property will be deprecated and replaced by - appliedScopeProperties instead for Single AppliedScopeType. - :paramtype applied_scopes: list[str] - :keyword applied_scope_properties: Properties specific to applied scope type. Not required if - not applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType - is ManagementGroup. - :paramtype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :keyword renew: Setting this to true will automatically purchase a new reservation on the - expiration date time. - :paramtype renew: bool - :keyword reserved_resource_properties: Properties specific to each reserved resource type. Not - required if not applicable. - :paramtype reserved_resource_properties: - ~azure.mgmt.reservations.models.PurchaseRequestPropertiesReservedResourceProperties - :keyword review_date_time: This is the date-time when the Azure hybrid benefit needs to be - reviewed. - :paramtype review_date_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.sku = sku - self.location = location - self.reserved_resource_type = reserved_resource_type - self.billing_scope_id = billing_scope_id - self.term = term - self.billing_plan = billing_plan - self.quantity = quantity - self.display_name = display_name - self.applied_scope_type = applied_scope_type - self.applied_scopes = applied_scopes - self.applied_scope_properties = applied_scope_properties - self.renew = renew - self.reserved_resource_properties = reserved_resource_properties - self.review_date_time = review_date_time - - -class PurchaseRequestPropertiesReservedResourceProperties(_serialization.Model): - """Properties specific to each reserved resource type. Not required if not applicable. - - :ivar instance_flexibility: Turning this on will apply the reservation discount to other VMs in - the same VM size group. Only specify for VirtualMachines reserved resource type. Known values - are: "On" and "Off". - :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility - """ - - _attribute_map = { - "instance_flexibility": {"key": "instanceFlexibility", "type": "str"}, - } - - def __init__( - self, *, instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, **kwargs: Any - ) -> None: - """ - :keyword instance_flexibility: Turning this on will apply the reservation discount to other VMs - in the same VM size group. Only specify for VirtualMachines reserved resource type. Known - values are: "On" and "Off". - :paramtype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility - """ - super().__init__(**kwargs) - self.instance_flexibility = instance_flexibility - - -class QuotaLimits(_serialization.Model): - """Quota limits. - - :ivar value: List of quotas (service limits). - :vartype value: list[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] - :ivar next_link: The URI for fetching the next page of quotas (service limits). When no more - pages exist, the value is null. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[CurrentQuotaLimitBase]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.CurrentQuotaLimitBase"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: List of quotas (service limits). - :paramtype value: list[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] - :keyword next_link: The URI for fetching the next page of quotas (service limits). When no more - pages exist, the value is null. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class QuotaLimitsResponse(_serialization.Model): - """Quotas (service limits) in the request response. - - :ivar value: List of quotas with the quota request status. - :vartype value: list[~azure.mgmt.reservations.models.CurrentQuotaLimit] - :ivar next_link: The URI for fetching the next page of quota limits. When no more pages exist, - the value is null. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[CurrentQuotaLimit]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.CurrentQuotaLimit"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: List of quotas with the quota request status. - :paramtype value: list[~azure.mgmt.reservations.models.CurrentQuotaLimit] - :keyword next_link: The URI for fetching the next page of quota limits. When no more pages - exist, the value is null. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class QuotaProperties(_serialization.Model): - """Quota properties for the resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar limit: Quota properties. - :vartype limit: int - :ivar current_value: Current usage value for the resource. - :vartype current_value: int - :ivar unit: The limit units, such as **count** and **bytes**. Use the unit field provided in - the response of the GET quota operation. - :vartype unit: str - :ivar name: Name of the resource provide by the resource provider. Use this property for - quotaRequests resource operations. - :vartype name: ~azure.mgmt.reservations.models.ResourceName - :ivar resource_type: The name of the resource type. Known values are: "standard", "dedicated", - "lowPriority", "shared", and "serviceSpecific". - :vartype resource_type: str or ~azure.mgmt.reservations.models.ResourceType - :ivar quota_period: The time period over which the quota usage values are summarized. For - example, P1D (per one day), PT1M (per one minute), and PT1S (per one second). This parameter is - optional because, for some resources such as compute, the time period is irrelevant. - :vartype quota_period: str - :ivar properties: Additional properties for the specified resource provider. - :vartype properties: JSON - """ - - _validation = { - "current_value": {"readonly": True}, - "quota_period": {"readonly": True}, - } - - _attribute_map = { - "limit": {"key": "limit", "type": "int"}, - "current_value": {"key": "currentValue", "type": "int"}, - "unit": {"key": "unit", "type": "str"}, - "name": {"key": "name", "type": "ResourceName"}, - "resource_type": {"key": "resourceType", "type": "str"}, - "quota_period": {"key": "quotaPeriod", "type": "str"}, - "properties": {"key": "properties", "type": "object"}, - } - - def __init__( - self, - *, - limit: Optional[int] = None, - unit: Optional[str] = None, - name: Optional["_models.ResourceName"] = None, - resource_type: Optional[Union[str, "_models.ResourceType"]] = None, - properties: Optional[JSON] = None, - **kwargs: Any - ) -> None: - """ - :keyword limit: Quota properties. - :paramtype limit: int - :keyword unit: The limit units, such as **count** and **bytes**. Use the unit field provided in - the response of the GET quota operation. - :paramtype unit: str - :keyword name: Name of the resource provide by the resource provider. Use this property for - quotaRequests resource operations. - :paramtype name: ~azure.mgmt.reservations.models.ResourceName - :keyword resource_type: The name of the resource type. Known values are: "standard", - "dedicated", "lowPriority", "shared", and "serviceSpecific". - :paramtype resource_type: str or ~azure.mgmt.reservations.models.ResourceType - :keyword properties: Additional properties for the specified resource provider. - :paramtype properties: JSON - """ - super().__init__(**kwargs) - self.limit = limit - self.current_value = None - self.unit = unit - self.name = name - self.resource_type = resource_type - self.quota_period = None - self.properties = properties - - -class QuotaRequestDetails(_serialization.Model): - """Quota request details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Quota request ID. - :vartype id: str - :ivar name: Quota request name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", - "Succeeded", "Failed", and "InProgress". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :ivar message: User friendly status message. - :vartype message: str - :ivar request_submit_time: The time when the quota request was submitted using format: - yyyy-MM-ddTHH:mm:ssZ as specified by the ISO 8601 standard. - :vartype request_submit_time: ~datetime.datetime - :ivar value: The quotaRequests. - :vartype value: list[~azure.mgmt.reservations.models.SubRequest] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "message": {"readonly": True}, - "request_submit_time": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "message": {"key": "properties.message", "type": "str"}, - "request_submit_time": {"key": "properties.requestSubmitTime", "type": "iso-8601"}, - "value": {"key": "properties.value", "type": "[SubRequest]"}, - } - - def __init__( - self, - *, - provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = None, - value: Optional[List["_models.SubRequest"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", - "Succeeded", "Failed", and "InProgress". - :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :keyword value: The quotaRequests. - :paramtype value: list[~azure.mgmt.reservations.models.SubRequest] - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.provisioning_state = provisioning_state - self.message = None - self.request_submit_time = None - self.value = value - - -class QuotaRequestDetailsList(_serialization.Model): - """Quota request details. - - :ivar value: The quota requests. - :vartype value: list[~azure.mgmt.reservations.models.QuotaRequestDetails] - :ivar next_link: The URI to fetch the next page of quota limits. When there are no more pages, - this is null. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[QuotaRequestDetails]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.QuotaRequestDetails"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: The quota requests. - :paramtype value: list[~azure.mgmt.reservations.models.QuotaRequestDetails] - :keyword next_link: The URI to fetch the next page of quota limits. When there are no more - pages, this is null. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class QuotaRequestOneResourceSubmitResponse(_serialization.Model): - """Response for the quota submission request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The quota request ID. - :vartype id: str - :ivar name: The name of the quota request. - :vartype name: str - :ivar type: Type of resource. "Microsoft.Capacity/ServiceLimits". - :vartype type: str - :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", - "Succeeded", "Failed", and "InProgress". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :ivar message: User friendly status message. - :vartype message: str - :ivar request_submit_time: The time when the quota request was submitted using format: - yyyy-MM-ddTHH:mm:ssZ as specified by the ISO 8601 standard. - :vartype request_submit_time: ~datetime.datetime - :ivar id_properties_id: The quota request ID. - :vartype id_properties_id: str - :ivar name_properties_name: The name of the quota request. - :vartype name_properties_name: str - :ivar type_properties_type: Type of resource. "Microsoft.Capacity/ServiceLimits". - :vartype type_properties_type: str - :ivar properties: Quota properties for the resource. - :vartype properties: ~azure.mgmt.reservations.models.QuotaProperties - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "message": {"readonly": True}, - "request_submit_time": {"readonly": True}, - "id_properties_id": {"readonly": True}, - "name_properties_name": {"readonly": True}, - "type_properties_type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "message": {"key": "properties.message", "type": "str"}, - "request_submit_time": {"key": "properties.requestSubmitTime", "type": "iso-8601"}, - "id_properties_id": {"key": "properties.properties.id", "type": "str"}, - "name_properties_name": {"key": "properties.properties.name", "type": "str"}, - "type_properties_type": {"key": "properties.properties.type", "type": "str"}, - "properties": {"key": "properties.properties.properties", "type": "QuotaProperties"}, - } - - def __init__(self, *, properties: Optional["_models.QuotaProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Quota properties for the resource. - :paramtype properties: ~azure.mgmt.reservations.models.QuotaProperties - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.provisioning_state = None - self.message = None - self.request_submit_time = None - self.id_properties_id = None - self.name_properties_name = None - self.type_properties_type = None - self.properties = properties - - -class QuotaRequestProperties(_serialization.Model): - """The details of quota request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", - "Succeeded", "Failed", and "InProgress". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :ivar message: User friendly status message. - :vartype message: str - :ivar request_submit_time: The time when the quota request was submitted using format: - yyyy-MM-ddTHH:mm:ssZ as specified by the ISO 8601 standard. - :vartype request_submit_time: ~datetime.datetime - :ivar value: The quotaRequests. - :vartype value: list[~azure.mgmt.reservations.models.SubRequest] - """ - - _validation = { - "message": {"readonly": True}, - "request_submit_time": {"readonly": True}, - } - - _attribute_map = { - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "request_submit_time": {"key": "requestSubmitTime", "type": "iso-8601"}, - "value": {"key": "value", "type": "[SubRequest]"}, - } - - def __init__( - self, - *, - provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = None, - value: Optional[List["_models.SubRequest"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", - "Succeeded", "Failed", and "InProgress". - :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :keyword value: The quotaRequests. - :paramtype value: list[~azure.mgmt.reservations.models.SubRequest] - """ - super().__init__(**kwargs) - self.provisioning_state = provisioning_state - self.message = None - self.request_submit_time = None - self.value = value - - -class QuotaRequestSubmitResponse(_serialization.Model): - """Response for the quota submission request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The quota request ID. - :vartype id: str - :ivar name: The name of the quota request. - :vartype name: str - :ivar properties: The quota request details. - :vartype properties: ~azure.mgmt.reservations.models.QuotaRequestProperties - :ivar type: Type of resource. "Microsoft.Capacity/serviceLimits". - :vartype type: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "properties": {"key": "properties", "type": "QuotaRequestProperties"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, properties: Optional["_models.QuotaRequestProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: The quota request details. - :paramtype properties: ~azure.mgmt.reservations.models.QuotaRequestProperties - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.properties = properties - self.type = None - - -class QuotaRequestSubmitResponse201(_serialization.Model): - """Response with request ID that the quota request was accepted. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The quota request ID. Use the requestId parameter to check the request status. - :vartype id: str - :ivar name: Operation ID. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar provisioning_state: The details of the quota request status. Known values are: - "Accepted", "Invalid", "Succeeded", "Failed", and "InProgress". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :ivar message: A user friendly message. - :vartype message: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "message": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "message": {"key": "properties.message", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.provisioning_state = None - self.message = None - - -class RefundBillingInformation(_serialization.Model): - """billing information. - - :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". - :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :ivar completed_transactions: The number of completed transactions in this reservation's - payment. - :vartype completed_transactions: int - :ivar total_transactions: The number of total transactions in this reservation's payment. - :vartype total_transactions: int - :ivar billing_currency_total_paid_amount: Pricing information containing the amount and the - currency code. - :vartype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price - :ivar billing_currency_prorated_amount: Pricing information containing the amount and the - currency code. - :vartype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price - :ivar billing_currency_remaining_commitment_amount: Pricing information containing the amount - and the currency code. - :vartype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price - """ - - _attribute_map = { - "billing_plan": {"key": "billingPlan", "type": "str"}, - "completed_transactions": {"key": "completedTransactions", "type": "int"}, - "total_transactions": {"key": "totalTransactions", "type": "int"}, - "billing_currency_total_paid_amount": {"key": "billingCurrencyTotalPaidAmount", "type": "Price"}, - "billing_currency_prorated_amount": {"key": "billingCurrencyProratedAmount", "type": "Price"}, - "billing_currency_remaining_commitment_amount": { - "key": "billingCurrencyRemainingCommitmentAmount", - "type": "Price", - }, - } - - def __init__( - self, - *, - billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, - completed_transactions: Optional[int] = None, - total_transactions: Optional[int] = None, - billing_currency_total_paid_amount: Optional["_models.Price"] = None, - billing_currency_prorated_amount: Optional["_models.Price"] = None, - billing_currency_remaining_commitment_amount: Optional["_models.Price"] = None, - **kwargs: Any - ) -> None: - """ - :keyword billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". - :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :keyword completed_transactions: The number of completed transactions in this reservation's - payment. - :paramtype completed_transactions: int - :keyword total_transactions: The number of total transactions in this reservation's payment. - :paramtype total_transactions: int - :keyword billing_currency_total_paid_amount: Pricing information containing the amount and the - currency code. - :paramtype billing_currency_total_paid_amount: ~azure.mgmt.reservations.models.Price - :keyword billing_currency_prorated_amount: Pricing information containing the amount and the - currency code. - :paramtype billing_currency_prorated_amount: ~azure.mgmt.reservations.models.Price - :keyword billing_currency_remaining_commitment_amount: Pricing information containing the - amount and the currency code. - :paramtype billing_currency_remaining_commitment_amount: ~azure.mgmt.reservations.models.Price - """ - super().__init__(**kwargs) - self.billing_plan = billing_plan - self.completed_transactions = completed_transactions - self.total_transactions = total_transactions - self.billing_currency_total_paid_amount = billing_currency_total_paid_amount - self.billing_currency_prorated_amount = billing_currency_prorated_amount - self.billing_currency_remaining_commitment_amount = billing_currency_remaining_commitment_amount - - -class RefundPolicyError(_serialization.Model): - """error details. - - :ivar code: Error code describing the reason that service is not able to process the incoming - request. Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", - "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", - "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", - "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", - "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", - "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", - "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", - "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", - "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", - "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", - "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", - "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", - "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", - "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", - "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", - "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", - "BillingTransientError", "BillingError", "FulfillmentConfigurationError", - "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", - "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and - "RefundLimitExceeded". - :vartype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode - :ivar message: - :vartype message: str - """ - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - } - - def __init__( - self, - *, - code: Optional[Union[str, "_models.ErrorResponseCode"]] = None, - message: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword code: Error code describing the reason that service is not able to process the - incoming request. Known values are: "NotSpecified", "InternalServerError", "ServerTimeout", - "AuthorizationFailed", "BadRequest", "ClientCertificateThumbprintNotSet", - "InvalidRequestContent", "OperationFailed", "HttpMethodNotSupported", "InvalidRequestUri", - "MissingTenantId", "InvalidTenantId", "InvalidReservationOrderId", "InvalidReservationId", - "ReservationIdNotInReservationOrder", "ReservationOrderNotFound", "InvalidSubscriptionId", - "InvalidAccessToken", "InvalidLocationId", "UnauthenticatedRequestsThrottled", - "InvalidHealthCheckType", "Forbidden", "BillingScopeIdCannotBeChanged", - "AppliedScopesNotAssociatedWithCommerceAccount", "PatchValuesSameAsExisting", - "RoleAssignmentCreationFailed", "ReservationOrderCreationFailed", "ReservationOrderNotEnabled", - "CapacityUpdateScopesFailed", "UnsupportedReservationTerm", "ReservationOrderIdAlreadyExists", - "RiskCheckFailed", "CreateQuoteFailed", "ActivateQuoteFailed", "NonsupportedAccountId", - "PaymentInstrumentNotFound", "MissingAppliedScopesForSingle", "NoValidReservationsToReRate", - "ReRateOnlyAllowedForEA", "OperationCannotBePerformedInCurrentState", - "InvalidSingleAppliedScopesCount", "InvalidFulfillmentRequestParameters", - "NotSupportedCountry", "InvalidRefundQuantity", "PurchaseError", "BillingCustomerInputError", - "BillingPaymentInstrumentSoftError", "BillingPaymentInstrumentHardError", - "BillingTransientError", "BillingError", "FulfillmentConfigurationError", - "FulfillmentOutOfStockError", "FulfillmentTransientError", "FulfillmentError", - "CalculatePriceFailed", "AppliedScopesSameAsExisting", "SelfServiceRefundNotSupported", and - "RefundLimitExceeded". - :paramtype code: str or ~azure.mgmt.reservations.models.ErrorResponseCode - :keyword message: - :paramtype message: str - """ - super().__init__(**kwargs) - self.code = code - self.message = message - - -class RefundPolicyResult(_serialization.Model): - """Refund policy result. - - :ivar properties: Refund policy result property. - :vartype properties: ~azure.mgmt.reservations.models.RefundPolicyResultProperty - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "RefundPolicyResultProperty"}, - } - - def __init__(self, *, properties: Optional["_models.RefundPolicyResultProperty"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Refund policy result property. - :paramtype properties: ~azure.mgmt.reservations.models.RefundPolicyResultProperty - """ - super().__init__(**kwargs) - self.properties = properties - - -class RefundPolicyResultProperty(_serialization.Model): - """Refund policy result property. - - :ivar consumed_refunds_total: Pricing information containing the amount and the currency code. - :vartype consumed_refunds_total: ~azure.mgmt.reservations.models.Price - :ivar max_refund_limit: Pricing information containing the amount and the currency code. - :vartype max_refund_limit: ~azure.mgmt.reservations.models.Price - :ivar policy_errors: Refund Policy errors. - :vartype policy_errors: list[~azure.mgmt.reservations.models.RefundPolicyError] - """ - - _attribute_map = { - "consumed_refunds_total": {"key": "consumedRefundsTotal", "type": "Price"}, - "max_refund_limit": {"key": "maxRefundLimit", "type": "Price"}, - "policy_errors": {"key": "policyErrors", "type": "[RefundPolicyError]"}, - } - - def __init__( - self, - *, - consumed_refunds_total: Optional["_models.Price"] = None, - max_refund_limit: Optional["_models.Price"] = None, - policy_errors: Optional[List["_models.RefundPolicyError"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword consumed_refunds_total: Pricing information containing the amount and the currency - code. - :paramtype consumed_refunds_total: ~azure.mgmt.reservations.models.Price - :keyword max_refund_limit: Pricing information containing the amount and the currency code. - :paramtype max_refund_limit: ~azure.mgmt.reservations.models.Price - :keyword policy_errors: Refund Policy errors. - :paramtype policy_errors: list[~azure.mgmt.reservations.models.RefundPolicyError] - """ - super().__init__(**kwargs) - self.consumed_refunds_total = consumed_refunds_total - self.max_refund_limit = max_refund_limit - self.policy_errors = policy_errors - - -class RefundRequest(_serialization.Model): - """Request containing information needed for returning reservation. - - :ivar properties: Properties needed for refund request including the session id from calculate - refund, the scope, the reservation to be returned and the return reason. - :vartype properties: ~azure.mgmt.reservations.models.RefundRequestProperties - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "RefundRequestProperties"}, - } - - def __init__(self, *, properties: Optional["_models.RefundRequestProperties"] = None, **kwargs: Any) -> None: - """ - :keyword properties: Properties needed for refund request including the session id from - calculate refund, the scope, the reservation to be returned and the return reason. - :paramtype properties: ~azure.mgmt.reservations.models.RefundRequestProperties - """ - super().__init__(**kwargs) - self.properties = properties - - -class RefundRequestProperties(_serialization.Model): - """Properties needed for refund request including the session id from calculate refund, the scope, - the reservation to be returned and the return reason. - - :ivar session_id: SessionId that was returned by CalculateRefund API. - :vartype session_id: str - :ivar scope: The scope of the refund, e.g. Reservation. - :vartype scope: str - :ivar reservation_to_return: Reservation to return. - :vartype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn - :ivar return_reason: The reason of returning the reservation. - :vartype return_reason: str - """ - - _attribute_map = { - "session_id": {"key": "sessionId", "type": "str"}, - "scope": {"key": "scope", "type": "str"}, - "reservation_to_return": {"key": "reservationToReturn", "type": "ReservationToReturn"}, - "return_reason": {"key": "returnReason", "type": "str"}, - } - - def __init__( - self, - *, - session_id: Optional[str] = None, - scope: Optional[str] = None, - reservation_to_return: Optional["_models.ReservationToReturn"] = None, - return_reason: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword session_id: SessionId that was returned by CalculateRefund API. - :paramtype session_id: str - :keyword scope: The scope of the refund, e.g. Reservation. - :paramtype scope: str - :keyword reservation_to_return: Reservation to return. - :paramtype reservation_to_return: ~azure.mgmt.reservations.models.ReservationToReturn - :keyword return_reason: The reason of returning the reservation. - :paramtype return_reason: str - """ - super().__init__(**kwargs) - self.session_id = session_id - self.scope = scope - self.reservation_to_return = reservation_to_return - self.return_reason = return_reason - - -class RefundResponse(_serialization.Model): - """The response of refund request containing refund information of reservation. - - :ivar id: Fully qualified identifier of the reservation being returned. - :vartype id: str - :ivar properties: The refund properties of reservation. - :vartype properties: ~azure.mgmt.reservations.models.RefundResponseProperties - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "properties": {"key": "properties", "type": "RefundResponseProperties"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - properties: Optional["_models.RefundResponseProperties"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Fully qualified identifier of the reservation being returned. - :paramtype id: str - :keyword properties: The refund properties of reservation. - :paramtype properties: ~azure.mgmt.reservations.models.RefundResponseProperties - """ - super().__init__(**kwargs) - self.id = id - self.properties = properties - - -class RefundResponseProperties(_serialization.Model): - """The refund properties of reservation. - - :ivar session_id: Refund session identifier. - :vartype session_id: str - :ivar quantity: Quantity to be returned. - :vartype quantity: int - :ivar billing_refund_amount: Pricing information containing the amount and the currency code. - :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price - :ivar pricing_refund_amount: Pricing information containing the amount and the currency code. - :vartype pricing_refund_amount: ~azure.mgmt.reservations.models.Price - :ivar policy_result: Refund policy result. - :vartype policy_result: ~azure.mgmt.reservations.models.RefundPolicyResult - :ivar billing_information: billing information. - :vartype billing_information: ~azure.mgmt.reservations.models.RefundBillingInformation - """ - - _attribute_map = { - "session_id": {"key": "sessionId", "type": "str"}, - "quantity": {"key": "quantity", "type": "int"}, - "billing_refund_amount": {"key": "billingRefundAmount", "type": "Price"}, - "pricing_refund_amount": {"key": "pricingRefundAmount", "type": "Price"}, - "policy_result": {"key": "policyResult", "type": "RefundPolicyResult"}, - "billing_information": {"key": "billingInformation", "type": "RefundBillingInformation"}, - } - - def __init__( - self, - *, - session_id: Optional[str] = None, - quantity: Optional[int] = None, - billing_refund_amount: Optional["_models.Price"] = None, - pricing_refund_amount: Optional["_models.Price"] = None, - policy_result: Optional["_models.RefundPolicyResult"] = None, - billing_information: Optional["_models.RefundBillingInformation"] = None, - **kwargs: Any - ) -> None: - """ - :keyword session_id: Refund session identifier. - :paramtype session_id: str - :keyword quantity: Quantity to be returned. - :paramtype quantity: int - :keyword billing_refund_amount: Pricing information containing the amount and the currency - code. - :paramtype billing_refund_amount: ~azure.mgmt.reservations.models.Price - :keyword pricing_refund_amount: Pricing information containing the amount and the currency - code. - :paramtype pricing_refund_amount: ~azure.mgmt.reservations.models.Price - :keyword policy_result: Refund policy result. - :paramtype policy_result: ~azure.mgmt.reservations.models.RefundPolicyResult - :keyword billing_information: billing information. - :paramtype billing_information: ~azure.mgmt.reservations.models.RefundBillingInformation - """ - super().__init__(**kwargs) - self.session_id = session_id - self.quantity = quantity - self.billing_refund_amount = billing_refund_amount - self.pricing_refund_amount = pricing_refund_amount - self.policy_result = policy_result - self.billing_information = billing_information - - -class RenewPropertiesResponse(_serialization.Model): - """The renew properties for a reservation. - - :ivar purchase_properties: The request for reservation purchase. - :vartype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest - :ivar pricing_currency_total: Amount that Microsoft uses for record. Used during refund for - calculating refund limit. Tax is not included. This is locked price 30 days before expiry. - :vartype pricing_currency_total: - ~azure.mgmt.reservations.models.RenewPropertiesResponsePricingCurrencyTotal - :ivar billing_currency_total: Currency and amount that customer will be charged in customer's - local currency for renewal purchase. Tax is not included. - :vartype billing_currency_total: - ~azure.mgmt.reservations.models.RenewPropertiesResponseBillingCurrencyTotal - """ - - _attribute_map = { - "purchase_properties": {"key": "purchaseProperties", "type": "PurchaseRequest"}, - "pricing_currency_total": { - "key": "pricingCurrencyTotal", - "type": "RenewPropertiesResponsePricingCurrencyTotal", - }, - "billing_currency_total": { - "key": "billingCurrencyTotal", - "type": "RenewPropertiesResponseBillingCurrencyTotal", - }, - } - - def __init__( - self, - *, - purchase_properties: Optional["_models.PurchaseRequest"] = None, - pricing_currency_total: Optional["_models.RenewPropertiesResponsePricingCurrencyTotal"] = None, - billing_currency_total: Optional["_models.RenewPropertiesResponseBillingCurrencyTotal"] = None, - **kwargs: Any - ) -> None: - """ - :keyword purchase_properties: The request for reservation purchase. - :paramtype purchase_properties: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword pricing_currency_total: Amount that Microsoft uses for record. Used during refund for - calculating refund limit. Tax is not included. This is locked price 30 days before expiry. - :paramtype pricing_currency_total: - ~azure.mgmt.reservations.models.RenewPropertiesResponsePricingCurrencyTotal - :keyword billing_currency_total: Currency and amount that customer will be charged in - customer's local currency for renewal purchase. Tax is not included. - :paramtype billing_currency_total: - ~azure.mgmt.reservations.models.RenewPropertiesResponseBillingCurrencyTotal - """ - super().__init__(**kwargs) - self.purchase_properties = purchase_properties - self.pricing_currency_total = pricing_currency_total - self.billing_currency_total = billing_currency_total - - -class RenewPropertiesResponseBillingCurrencyTotal(_serialization.Model): - """Currency and amount that customer will be charged in customer's local currency for renewal - purchase. Tax is not included. - - :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase - record. - :vartype currency_code: str - :ivar amount: - :vartype amount: float - """ - - _attribute_map = { - "currency_code": {"key": "currencyCode", "type": "str"}, - "amount": {"key": "amount", "type": "float"}, - } - - def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs: Any) -> None: - """ - :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this - purchase record. - :paramtype currency_code: str - :keyword amount: - :paramtype amount: float - """ - super().__init__(**kwargs) - self.currency_code = currency_code - self.amount = amount - - -class RenewPropertiesResponsePricingCurrencyTotal(_serialization.Model): - """Amount that Microsoft uses for record. Used during refund for calculating refund limit. Tax is - not included. This is locked price 30 days before expiry. - - :ivar currency_code: The ISO 4217 3-letter currency code for the currency used by this purchase - record. - :vartype currency_code: str - :ivar amount: - :vartype amount: float - """ - - _attribute_map = { - "currency_code": {"key": "currencyCode", "type": "str"}, - "amount": {"key": "amount", "type": "float"}, - } - - def __init__(self, *, currency_code: Optional[str] = None, amount: Optional[float] = None, **kwargs: Any) -> None: - """ - :keyword currency_code: The ISO 4217 3-letter currency code for the currency used by this - purchase record. - :paramtype currency_code: str - :keyword amount: - :paramtype amount: float - """ - super().__init__(**kwargs) - self.currency_code = currency_code - self.amount = amount - - -class ReservationList(_serialization.Model): - """List of ``Reservation``\ s. - - :ivar value: - :vartype value: list[~azure.mgmt.reservations.models.ReservationResponse] - :ivar next_link: Url to get the next page of reservations. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[ReservationResponse]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.ReservationResponse"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: - :paramtype value: list[~azure.mgmt.reservations.models.ReservationResponse] - :keyword next_link: Url to get the next page of reservations. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ReservationMergeProperties(_serialization.Model): - """Properties of reservation merge. - - :ivar merge_destination: Reservation resource id Created due to the merge. Format of the - resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype merge_destination: str - :ivar merge_sources: Resource ids of the source reservation's merged to form this reservation. - Format of the resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype merge_sources: list[str] - """ - - _attribute_map = { - "merge_destination": {"key": "mergeDestination", "type": "str"}, - "merge_sources": {"key": "mergeSources", "type": "[str]"}, - } - - def __init__( - self, *, merge_destination: Optional[str] = None, merge_sources: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword merge_destination: Reservation resource id Created due to the merge. Format of the - resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype merge_destination: str - :keyword merge_sources: Resource ids of the source reservation's merged to form this - reservation. Format of the resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype merge_sources: list[str] - """ - super().__init__(**kwargs) - self.merge_destination = merge_destination - self.merge_sources = merge_sources - - -class ReservationOrderBillingPlanInformation(_serialization.Model): - """Information describing the type of billing plan for this reservation. - - :ivar pricing_currency_total: Amount of money to be paid for the Order. Tax is not included. - :vartype pricing_currency_total: ~azure.mgmt.reservations.models.Price - :ivar start_date: Date when the billing plan has started. - :vartype start_date: ~datetime.date - :ivar next_payment_due_date: For recurring billing plans, indicates the date when next payment - will be processed. Null when total is paid off. - :vartype next_payment_due_date: ~datetime.date - :ivar transactions: - :vartype transactions: list[~azure.mgmt.reservations.models.PaymentDetail] - """ - - _attribute_map = { - "pricing_currency_total": {"key": "pricingCurrencyTotal", "type": "Price"}, - "start_date": {"key": "startDate", "type": "date"}, - "next_payment_due_date": {"key": "nextPaymentDueDate", "type": "date"}, - "transactions": {"key": "transactions", "type": "[PaymentDetail]"}, - } - - def __init__( - self, - *, - pricing_currency_total: Optional["_models.Price"] = None, - start_date: Optional[datetime.date] = None, - next_payment_due_date: Optional[datetime.date] = None, - transactions: Optional[List["_models.PaymentDetail"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword pricing_currency_total: Amount of money to be paid for the Order. Tax is not included. - :paramtype pricing_currency_total: ~azure.mgmt.reservations.models.Price - :keyword start_date: Date when the billing plan has started. - :paramtype start_date: ~datetime.date - :keyword next_payment_due_date: For recurring billing plans, indicates the date when next - payment will be processed. Null when total is paid off. - :paramtype next_payment_due_date: ~datetime.date - :keyword transactions: - :paramtype transactions: list[~azure.mgmt.reservations.models.PaymentDetail] - """ - super().__init__(**kwargs) - self.pricing_currency_total = pricing_currency_total - self.start_date = start_date - self.next_payment_due_date = next_payment_due_date - self.transactions = transactions - - -class ReservationOrderList(_serialization.Model): - """List of ``ReservationOrder``\ s. - - :ivar value: - :vartype value: list[~azure.mgmt.reservations.models.ReservationOrderResponse] - :ivar next_link: Url to get the next page of reservationOrders. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[ReservationOrderResponse]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.ReservationOrderResponse"]] = None, - next_link: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword value: - :paramtype value: list[~azure.mgmt.reservations.models.ReservationOrderResponse] - :keyword next_link: Url to get the next page of reservationOrders. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class ReservationOrderResponse(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Details of a reservation order being returned. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar etag: - :vartype etag: int - :ivar id: Identifier of the reservation. - :vartype id: str - :ivar name: Name of the reservation. - :vartype name: str - :ivar type: Type of resource. "Microsoft.Capacity/reservations". - :vartype type: str - :ivar system_data: Metadata pertaining to creation and last modification of the resource. - :vartype system_data: ~azure.mgmt.reservations.models.SystemData - :ivar display_name: Friendly name for user to easily identified the reservation. - :vartype display_name: str - :ivar request_date_time: This is the DateTime when the reservation was initially requested for - purchase. - :vartype request_date_time: ~datetime.datetime - :ivar created_date_time: This is the DateTime when the reservation was created. - :vartype created_date_time: ~datetime.datetime - :ivar expiry_date: This is the date when the reservation will expire. - :vartype expiry_date: ~datetime.date - :ivar expiry_date_time: This is the date-time when the reservation will expire. - :vartype expiry_date_time: ~datetime.datetime - :ivar benefit_start_time: This is the DateTime when the reservation benefit started. - :vartype benefit_start_time: ~datetime.datetime - :ivar original_quantity: Total Quantity of the skus purchased in the reservation. - :vartype original_quantity: int - :ivar term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". - :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :ivar provisioning_state: Current state of the reservation. Known values are: "Creating", - "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", - "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and - "Merged". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState - :ivar billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". - :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :ivar plan_information: Information describing the type of billing plan for this reservation. - :vartype plan_information: - ~azure.mgmt.reservations.models.ReservationOrderBillingPlanInformation - :ivar reservations: - :vartype reservations: list[~azure.mgmt.reservations.models.ReservationResponse] - :ivar review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be - reviewed. - :vartype review_date_time: ~datetime.datetime - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "etag": {"key": "etag", "type": "int"}, - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "request_date_time": {"key": "properties.requestDateTime", "type": "iso-8601"}, - "created_date_time": {"key": "properties.createdDateTime", "type": "iso-8601"}, - "expiry_date": {"key": "properties.expiryDate", "type": "date"}, - "expiry_date_time": {"key": "properties.expiryDateTime", "type": "iso-8601"}, - "benefit_start_time": {"key": "properties.benefitStartTime", "type": "iso-8601"}, - "original_quantity": {"key": "properties.originalQuantity", "type": "int"}, - "term": {"key": "properties.term", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "billing_plan": {"key": "properties.billingPlan", "type": "str"}, - "plan_information": {"key": "properties.planInformation", "type": "ReservationOrderBillingPlanInformation"}, - "reservations": {"key": "properties.reservations", "type": "[ReservationResponse]"}, - "review_date_time": {"key": "properties.reviewDateTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - etag: Optional[int] = None, - display_name: Optional[str] = None, - request_date_time: Optional[datetime.datetime] = None, - created_date_time: Optional[datetime.datetime] = None, - expiry_date: Optional[datetime.date] = None, - expiry_date_time: Optional[datetime.datetime] = None, - benefit_start_time: Optional[datetime.datetime] = None, - original_quantity: Optional[int] = None, - term: Optional[Union[str, "_models.ReservationTerm"]] = None, - provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, - billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, - plan_information: Optional["_models.ReservationOrderBillingPlanInformation"] = None, - reservations: Optional[List["_models.ReservationResponse"]] = None, - review_date_time: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> None: - """ - :keyword etag: - :paramtype etag: int - :keyword display_name: Friendly name for user to easily identified the reservation. - :paramtype display_name: str - :keyword request_date_time: This is the DateTime when the reservation was initially requested - for purchase. - :paramtype request_date_time: ~datetime.datetime - :keyword created_date_time: This is the DateTime when the reservation was created. - :paramtype created_date_time: ~datetime.datetime - :keyword expiry_date: This is the date when the reservation will expire. - :paramtype expiry_date: ~datetime.date - :keyword expiry_date_time: This is the date-time when the reservation will expire. - :paramtype expiry_date_time: ~datetime.datetime - :keyword benefit_start_time: This is the DateTime when the reservation benefit started. - :paramtype benefit_start_time: ~datetime.datetime - :keyword original_quantity: Total Quantity of the skus purchased in the reservation. - :paramtype original_quantity: int - :keyword term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". - :paramtype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :keyword provisioning_state: Current state of the reservation. Known values are: "Creating", - "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", - "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and - "Merged". - :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState - :keyword billing_plan: Represent the billing plans. Known values are: "Upfront" and "Monthly". - :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :keyword plan_information: Information describing the type of billing plan for this - reservation. - :paramtype plan_information: - ~azure.mgmt.reservations.models.ReservationOrderBillingPlanInformation - :keyword reservations: - :paramtype reservations: list[~azure.mgmt.reservations.models.ReservationResponse] - :keyword review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be - reviewed. - :paramtype review_date_time: ~datetime.datetime - """ - super().__init__(**kwargs) - self.etag = etag - self.id = None - self.name = None - self.type = None - self.system_data = None - self.display_name = display_name - self.request_date_time = request_date_time - self.created_date_time = created_date_time - self.expiry_date = expiry_date - self.expiry_date_time = expiry_date_time - self.benefit_start_time = benefit_start_time - self.original_quantity = original_quantity - self.term = term - self.provisioning_state = provisioning_state - self.billing_plan = billing_plan - self.plan_information = plan_information - self.reservations = reservations - self.review_date_time = review_date_time - - -class ReservationResponse(ProxyResource): - """The definition of the reservation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. E.g. - "/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.reservations.models.SystemData - :ivar location: The Azure region where the reserved resource lives. - :vartype location: str - :ivar etag: - :vartype etag: int - :ivar sku: The sku information associated to this reservation. - :vartype sku: ~azure.mgmt.reservations.models.SkuName - :ivar properties: The properties associated to this reservation. - :vartype properties: ~azure.mgmt.reservations.models.ReservationsProperties - :ivar kind: Resource Provider type to be reserved. Default value is "Microsoft.Compute". - :vartype kind: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "location": {"key": "location", "type": "str"}, - "etag": {"key": "etag", "type": "int"}, - "sku": {"key": "sku", "type": "SkuName"}, - "properties": {"key": "properties", "type": "ReservationsProperties"}, - "kind": {"key": "kind", "type": "str"}, - } - - def __init__( - self, - *, - location: Optional[str] = None, - etag: Optional[int] = None, - sku: Optional["_models.SkuName"] = None, - properties: Optional["_models.ReservationsProperties"] = None, - kind: Optional[Literal["Microsoft.Compute"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: The Azure region where the reserved resource lives. - :paramtype location: str - :keyword etag: - :paramtype etag: int - :keyword sku: The sku information associated to this reservation. - :paramtype sku: ~azure.mgmt.reservations.models.SkuName - :keyword properties: The properties associated to this reservation. - :paramtype properties: ~azure.mgmt.reservations.models.ReservationsProperties - :keyword kind: Resource Provider type to be reserved. Default value is "Microsoft.Compute". - :paramtype kind: str - """ - super().__init__(**kwargs) - self.location = location - self.etag = etag - self.sku = sku - self.properties = properties - self.kind = kind - - -class ReservationsListResult(_serialization.Model): - """The list of reservations and summary of roll out count of reservations in each state. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of reservations. - :vartype value: list[~azure.mgmt.reservations.models.ReservationResponse] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - :ivar summary: The roll out count summary of the reservations. - :vartype summary: ~azure.mgmt.reservations.models.ReservationSummary - """ - - _validation = { - "value": {"readonly": True}, - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[ReservationResponse]"}, - "next_link": {"key": "nextLink", "type": "str"}, - "summary": {"key": "summary", "type": "ReservationSummary"}, - } - - def __init__(self, *, summary: Optional["_models.ReservationSummary"] = None, **kwargs: Any) -> None: - """ - :keyword summary: The roll out count summary of the reservations. - :paramtype summary: ~azure.mgmt.reservations.models.ReservationSummary - """ - super().__init__(**kwargs) - self.value = None - self.next_link = None - self.summary = summary - - -class ReservationSplitProperties(_serialization.Model): - """Properties of reservation split. - - :ivar split_destinations: List of destination resource id that are created due to split. Format - of the resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype split_destinations: list[str] - :ivar split_source: Resource id of the reservation from which this is split. Format of the - resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype split_source: str - """ - - _attribute_map = { - "split_destinations": {"key": "splitDestinations", "type": "[str]"}, - "split_source": {"key": "splitSource", "type": "str"}, - } - - def __init__( - self, *, split_destinations: Optional[List[str]] = None, split_source: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword split_destinations: List of destination resource id that are created due to split. - Format of the resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype split_destinations: list[str] - :keyword split_source: Resource id of the reservation from which this is split. Format of the - resource id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype split_source: str - """ - super().__init__(**kwargs) - self.split_destinations = split_destinations - self.split_source = split_source - - -class ReservationsProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes - """The properties of the reservations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar reserved_resource_type: The type of the resource that is being reserved. Known values - are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", - "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", - "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", - "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", - "SqlEdge", and "VirtualMachineSoftware". - :vartype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType - :ivar instance_flexibility: Allows reservation discount to be applied across skus within the - same auto fit group. Not all skus support instance size flexibility. Known values are: "On" and - "Off". - :vartype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility - :ivar display_name: Friendly name for user to easily identify the reservation. - :vartype display_name: str - :ivar applied_scopes: The list of applied scopes. - :vartype applied_scopes: list[str] - :ivar applied_scope_type: The applied scope type. Known values are: "Single", "Shared", and - "ManagementGroup". - :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :ivar archived: Indicates if the reservation is archived. - :vartype archived: bool - :ivar capabilities: Capabilities of the reservation. - :vartype capabilities: str - :ivar quantity: Quantity of the skus that are part of the reservation. - :vartype quantity: int - :ivar provisioning_state: Current state of the reservation. Known values are: "Creating", - "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", - "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and - "Merged". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState - :ivar effective_date_time: DateTime of the reservation starting when this version is effective - from. - :vartype effective_date_time: ~datetime.datetime - :ivar benefit_start_time: This is the DateTime when the reservation benefit started. - :vartype benefit_start_time: ~datetime.datetime - :ivar last_updated_date_time: DateTime of the last time the reservation was updated. - :vartype last_updated_date_time: ~datetime.datetime - :ivar expiry_date: This is the date when the reservation will expire. - :vartype expiry_date: ~datetime.date - :ivar expiry_date_time: This is the date-time when the reservation will expire. - :vartype expiry_date_time: ~datetime.datetime - :ivar review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be - reviewed. - :vartype review_date_time: ~datetime.datetime - :ivar sku_description: Description of the sku in english. - :vartype sku_description: str - :ivar extended_status_info: The message giving detailed information about the status code. - :vartype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo - :ivar billing_plan: The billing plan options available for this sku. Known values are: - "Upfront" and "Monthly". - :vartype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :ivar display_provisioning_state: The provisioning state of the reservation for display, e.g. - Succeeded. - :vartype display_provisioning_state: str - :ivar provisioning_sub_state: The provisioning sub-state of the reservation, e.g. Succeeded. - :vartype provisioning_sub_state: str - :ivar purchase_date: This is the date when the reservation was purchased. - :vartype purchase_date: ~datetime.date - :ivar purchase_date_time: This is the date-time when the reservation was purchased. - :vartype purchase_date_time: ~datetime.datetime - :ivar split_properties: Properties of reservation split. - :vartype split_properties: ~azure.mgmt.reservations.models.ReservationSplitProperties - :ivar merge_properties: Properties of reservation merge. - :vartype merge_properties: ~azure.mgmt.reservations.models.ReservationMergeProperties - :ivar swap_properties: Properties of reservation swap. - :vartype swap_properties: ~azure.mgmt.reservations.models.ReservationSwapProperties - :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not - applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is - ManagementGroup. - :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :ivar billing_scope_id: Subscription that will be charged for purchasing reservation or savings - plan. - :vartype billing_scope_id: str - :ivar renew: Setting this to true will automatically purchase a new reservation on the - expiration date time. - :vartype renew: bool - :ivar renew_source: Reservation Id of the reservation from which this reservation is renewed. - Format of the resource Id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype renew_source: str - :ivar renew_destination: Reservation Id of the reservation which is purchased because of renew. - Format of the resource Id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype renew_destination: str - :ivar renew_properties: The renew properties for a reservation. - :vartype renew_properties: ~azure.mgmt.reservations.models.RenewPropertiesResponse - :ivar term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". - :vartype term: str or ~azure.mgmt.reservations.models.ReservationTerm - :ivar user_friendly_applied_scope_type: The applied scope type of the reservation for display, - e.g. Shared. - :vartype user_friendly_applied_scope_type: str - :ivar user_friendly_renew_state: The renew state of the reservation for display, e.g. On. - :vartype user_friendly_renew_state: str - :ivar utilization: Reservation utilization. - :vartype utilization: ~azure.mgmt.reservations.models.ReservationsPropertiesUtilization - """ - - _validation = { - "last_updated_date_time": {"readonly": True}, - "display_provisioning_state": {"readonly": True}, - "provisioning_sub_state": {"readonly": True}, - "user_friendly_applied_scope_type": {"readonly": True}, - "user_friendly_renew_state": {"readonly": True}, - "utilization": {"readonly": True}, - } - - _attribute_map = { - "reserved_resource_type": {"key": "reservedResourceType", "type": "str"}, - "instance_flexibility": {"key": "instanceFlexibility", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, - "applied_scopes": {"key": "appliedScopes", "type": "[str]"}, - "applied_scope_type": {"key": "appliedScopeType", "type": "str"}, - "archived": {"key": "archived", "type": "bool"}, - "capabilities": {"key": "capabilities", "type": "str"}, - "quantity": {"key": "quantity", "type": "int"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "effective_date_time": {"key": "effectiveDateTime", "type": "iso-8601"}, - "benefit_start_time": {"key": "benefitStartTime", "type": "iso-8601"}, - "last_updated_date_time": {"key": "lastUpdatedDateTime", "type": "iso-8601"}, - "expiry_date": {"key": "expiryDate", "type": "date"}, - "expiry_date_time": {"key": "expiryDateTime", "type": "iso-8601"}, - "review_date_time": {"key": "reviewDateTime", "type": "iso-8601"}, - "sku_description": {"key": "skuDescription", "type": "str"}, - "extended_status_info": {"key": "extendedStatusInfo", "type": "ExtendedStatusInfo"}, - "billing_plan": {"key": "billingPlan", "type": "str"}, - "display_provisioning_state": {"key": "displayProvisioningState", "type": "str"}, - "provisioning_sub_state": {"key": "provisioningSubState", "type": "str"}, - "purchase_date": {"key": "purchaseDate", "type": "date"}, - "purchase_date_time": {"key": "purchaseDateTime", "type": "iso-8601"}, - "split_properties": {"key": "splitProperties", "type": "ReservationSplitProperties"}, - "merge_properties": {"key": "mergeProperties", "type": "ReservationMergeProperties"}, - "swap_properties": {"key": "swapProperties", "type": "ReservationSwapProperties"}, - "applied_scope_properties": {"key": "appliedScopeProperties", "type": "AppliedScopeProperties"}, - "billing_scope_id": {"key": "billingScopeId", "type": "str"}, - "renew": {"key": "renew", "type": "bool"}, - "renew_source": {"key": "renewSource", "type": "str"}, - "renew_destination": {"key": "renewDestination", "type": "str"}, - "renew_properties": {"key": "renewProperties", "type": "RenewPropertiesResponse"}, - "term": {"key": "term", "type": "str"}, - "user_friendly_applied_scope_type": {"key": "userFriendlyAppliedScopeType", "type": "str"}, - "user_friendly_renew_state": {"key": "userFriendlyRenewState", "type": "str"}, - "utilization": {"key": "utilization", "type": "ReservationsPropertiesUtilization"}, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - reserved_resource_type: Optional[Union[str, "_models.ReservedResourceType"]] = None, - instance_flexibility: Optional[Union[str, "_models.InstanceFlexibility"]] = None, - display_name: Optional[str] = None, - applied_scopes: Optional[List[str]] = None, - applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, - archived: Optional[bool] = None, - capabilities: Optional[str] = None, - quantity: Optional[int] = None, - provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = None, - effective_date_time: Optional[datetime.datetime] = None, - benefit_start_time: Optional[datetime.datetime] = None, - expiry_date: Optional[datetime.date] = None, - expiry_date_time: Optional[datetime.datetime] = None, - review_date_time: Optional[datetime.datetime] = None, - sku_description: Optional[str] = None, - extended_status_info: Optional["_models.ExtendedStatusInfo"] = None, - billing_plan: Optional[Union[str, "_models.ReservationBillingPlan"]] = None, - purchase_date: Optional[datetime.date] = None, - purchase_date_time: Optional[datetime.datetime] = None, - split_properties: Optional["_models.ReservationSplitProperties"] = None, - merge_properties: Optional["_models.ReservationMergeProperties"] = None, - swap_properties: Optional["_models.ReservationSwapProperties"] = None, - applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, - billing_scope_id: Optional[str] = None, - renew: bool = False, - renew_source: Optional[str] = None, - renew_destination: Optional[str] = None, - renew_properties: Optional["_models.RenewPropertiesResponse"] = None, - term: Optional[Union[str, "_models.ReservationTerm"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reserved_resource_type: The type of the resource that is being reserved. Known values - are: "VirtualMachines", "SqlDatabases", "SuseLinux", "CosmosDb", "RedHat", "SqlDataWarehouse", - "VMwareCloudSimple", "RedHatOsa", "Databricks", "AppService", "ManagedDisk", "BlockBlob", - "RedisCache", "AzureDataExplorer", "MySql", "MariaDb", "PostgreSql", "DedicatedHost", - "SapHana", "SqlAzureHybridBenefit", "AVS", "DataFactory", "NetAppStorage", "AzureFiles", - "SqlEdge", and "VirtualMachineSoftware". - :paramtype reserved_resource_type: str or ~azure.mgmt.reservations.models.ReservedResourceType - :keyword instance_flexibility: Allows reservation discount to be applied across skus within the - same auto fit group. Not all skus support instance size flexibility. Known values are: "On" and - "Off". - :paramtype instance_flexibility: str or ~azure.mgmt.reservations.models.InstanceFlexibility - :keyword display_name: Friendly name for user to easily identify the reservation. - :paramtype display_name: str - :keyword applied_scopes: The list of applied scopes. - :paramtype applied_scopes: list[str] - :keyword applied_scope_type: The applied scope type. Known values are: "Single", "Shared", and - "ManagementGroup". - :paramtype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :keyword archived: Indicates if the reservation is archived. - :paramtype archived: bool - :keyword capabilities: Capabilities of the reservation. - :paramtype capabilities: str - :keyword quantity: Quantity of the skus that are part of the reservation. - :paramtype quantity: int - :keyword provisioning_state: Current state of the reservation. Known values are: "Creating", - "PendingResourceHold", "ConfirmedResourceHold", "PendingBilling", "ConfirmedBilling", - "Created", "Succeeded", "Cancelled", "Expired", "BillingFailed", "Failed", "Split", and - "Merged". - :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.ProvisioningState - :keyword effective_date_time: DateTime of the reservation starting when this version is - effective from. - :paramtype effective_date_time: ~datetime.datetime - :keyword benefit_start_time: This is the DateTime when the reservation benefit started. - :paramtype benefit_start_time: ~datetime.datetime - :keyword expiry_date: This is the date when the reservation will expire. - :paramtype expiry_date: ~datetime.date - :keyword expiry_date_time: This is the date-time when the reservation will expire. - :paramtype expiry_date_time: ~datetime.datetime - :keyword review_date_time: This is the date-time when the Azure Hybrid Benefit needs to be - reviewed. - :paramtype review_date_time: ~datetime.datetime - :keyword sku_description: Description of the sku in english. - :paramtype sku_description: str - :keyword extended_status_info: The message giving detailed information about the status code. - :paramtype extended_status_info: ~azure.mgmt.reservations.models.ExtendedStatusInfo - :keyword billing_plan: The billing plan options available for this sku. Known values are: - "Upfront" and "Monthly". - :paramtype billing_plan: str or ~azure.mgmt.reservations.models.ReservationBillingPlan - :keyword purchase_date: This is the date when the reservation was purchased. - :paramtype purchase_date: ~datetime.date - :keyword purchase_date_time: This is the date-time when the reservation was purchased. - :paramtype purchase_date_time: ~datetime.datetime - :keyword split_properties: Properties of reservation split. - :paramtype split_properties: ~azure.mgmt.reservations.models.ReservationSplitProperties - :keyword merge_properties: Properties of reservation merge. - :paramtype merge_properties: ~azure.mgmt.reservations.models.ReservationMergeProperties - :keyword swap_properties: Properties of reservation swap. - :paramtype swap_properties: ~azure.mgmt.reservations.models.ReservationSwapProperties - :keyword applied_scope_properties: Properties specific to applied scope type. Not required if - not applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType - is ManagementGroup. - :paramtype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :keyword billing_scope_id: Subscription that will be charged for purchasing reservation or - savings plan. - :paramtype billing_scope_id: str - :keyword renew: Setting this to true will automatically purchase a new reservation on the - expiration date time. - :paramtype renew: bool - :keyword renew_source: Reservation Id of the reservation from which this reservation is - renewed. Format of the resource Id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype renew_source: str - :keyword renew_destination: Reservation Id of the reservation which is purchased because of - renew. Format of the resource Id is - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype renew_destination: str - :keyword renew_properties: The renew properties for a reservation. - :paramtype renew_properties: ~azure.mgmt.reservations.models.RenewPropertiesResponse - :keyword term: Represent the term of reservation. Known values are: "P1Y", "P3Y", and "P5Y". - :paramtype term: str or ~azure.mgmt.reservations.models.ReservationTerm - """ - super().__init__(**kwargs) - self.reserved_resource_type = reserved_resource_type - self.instance_flexibility = instance_flexibility - self.display_name = display_name - self.applied_scopes = applied_scopes - self.applied_scope_type = applied_scope_type - self.archived = archived - self.capabilities = capabilities - self.quantity = quantity - self.provisioning_state = provisioning_state - self.effective_date_time = effective_date_time - self.benefit_start_time = benefit_start_time - self.last_updated_date_time = None - self.expiry_date = expiry_date - self.expiry_date_time = expiry_date_time - self.review_date_time = review_date_time - self.sku_description = sku_description - self.extended_status_info = extended_status_info - self.billing_plan = billing_plan - self.display_provisioning_state = None - self.provisioning_sub_state = None - self.purchase_date = purchase_date - self.purchase_date_time = purchase_date_time - self.split_properties = split_properties - self.merge_properties = merge_properties - self.swap_properties = swap_properties - self.applied_scope_properties = applied_scope_properties - self.billing_scope_id = billing_scope_id - self.renew = renew - self.renew_source = renew_source - self.renew_destination = renew_destination - self.renew_properties = renew_properties - self.term = term - self.user_friendly_applied_scope_type = None - self.user_friendly_renew_state = None - self.utilization = None - - -class ReservationsPropertiesUtilization(_serialization.Model): - """Reservation utilization. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar trend: last 7 day utilization trend for a reservation. - :vartype trend: str - :ivar aggregates: The array of aggregates of a reservation's utilization. - :vartype aggregates: list[~azure.mgmt.reservations.models.ReservationUtilizationAggregates] - """ - - _validation = { - "trend": {"readonly": True}, - } - - _attribute_map = { - "trend": {"key": "trend", "type": "str"}, - "aggregates": {"key": "aggregates", "type": "[ReservationUtilizationAggregates]"}, - } - - def __init__( - self, *, aggregates: Optional[List["_models.ReservationUtilizationAggregates"]] = None, **kwargs: Any - ) -> None: - """ - :keyword aggregates: The array of aggregates of a reservation's utilization. - :paramtype aggregates: list[~azure.mgmt.reservations.models.ReservationUtilizationAggregates] - """ - super().__init__(**kwargs) - self.trend = None - self.aggregates = aggregates - - -class ReservationSummary(_serialization.Model): - """The roll up count summary of reservations in each state. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar succeeded_count: The number of reservation in Succeeded state. - :vartype succeeded_count: float - :ivar failed_count: The number of reservation in Failed state. - :vartype failed_count: float - :ivar expiring_count: The number of reservation in Expiring state. - :vartype expiring_count: float - :ivar expired_count: The number of reservation in Expired state. - :vartype expired_count: float - :ivar pending_count: The number of reservation in Pending state. - :vartype pending_count: float - :ivar cancelled_count: The number of reservation in Cancelled state. - :vartype cancelled_count: float - :ivar processing_count: The number of reservation in Processing state. - :vartype processing_count: float - :ivar warning_count: The number of reservation in Warning state. - :vartype warning_count: float - :ivar no_benefit_count: The number of reservation in NoBenefit state. - :vartype no_benefit_count: float - """ - - _validation = { - "succeeded_count": {"readonly": True}, - "failed_count": {"readonly": True}, - "expiring_count": {"readonly": True}, - "expired_count": {"readonly": True}, - "pending_count": {"readonly": True}, - "cancelled_count": {"readonly": True}, - "processing_count": {"readonly": True}, - "warning_count": {"readonly": True}, - "no_benefit_count": {"readonly": True}, - } - - _attribute_map = { - "succeeded_count": {"key": "succeededCount", "type": "float"}, - "failed_count": {"key": "failedCount", "type": "float"}, - "expiring_count": {"key": "expiringCount", "type": "float"}, - "expired_count": {"key": "expiredCount", "type": "float"}, - "pending_count": {"key": "pendingCount", "type": "float"}, - "cancelled_count": {"key": "cancelledCount", "type": "float"}, - "processing_count": {"key": "processingCount", "type": "float"}, - "warning_count": {"key": "warningCount", "type": "float"}, - "no_benefit_count": {"key": "noBenefitCount", "type": "float"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.succeeded_count = None - self.failed_count = None - self.expiring_count = None - self.expired_count = None - self.pending_count = None - self.cancelled_count = None - self.processing_count = None - self.warning_count = None - self.no_benefit_count = None - - -class ReservationSwapProperties(_serialization.Model): - """Properties of reservation swap. - - :ivar swap_source: Resource id of the source reservation that gets swapped. Format of the - resource id is - /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype swap_source: str - :ivar swap_destination: Reservation resource id that the original resource gets swapped to. - Format of the resource id is - /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype swap_destination: str - """ - - _attribute_map = { - "swap_source": {"key": "swapSource", "type": "str"}, - "swap_destination": {"key": "swapDestination", "type": "str"}, - } - - def __init__( - self, *, swap_source: Optional[str] = None, swap_destination: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword swap_source: Resource id of the source reservation that gets swapped. Format of the - resource id is - /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype swap_source: str - :keyword swap_destination: Reservation resource id that the original resource gets swapped to. - Format of the resource id is - /providers/microsoft.capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype swap_destination: str - """ - super().__init__(**kwargs) - self.swap_source = swap_source - self.swap_destination = swap_destination - - -class ReservationToExchange(_serialization.Model): - """Reservation refund details. - - :ivar reservation_id: Fully qualified id of the reservation being returned. - :vartype reservation_id: str - :ivar quantity: Quantity to be returned. - :vartype quantity: int - :ivar billing_refund_amount: Pricing information containing the amount and the currency code. - :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price - :ivar billing_information: billing information. - :vartype billing_information: ~azure.mgmt.reservations.models.BillingInformation - """ - - _attribute_map = { - "reservation_id": {"key": "reservationId", "type": "str"}, - "quantity": {"key": "quantity", "type": "int"}, - "billing_refund_amount": {"key": "billingRefundAmount", "type": "Price"}, - "billing_information": {"key": "billingInformation", "type": "BillingInformation"}, - } - - def __init__( - self, - *, - reservation_id: Optional[str] = None, - quantity: Optional[int] = None, - billing_refund_amount: Optional["_models.Price"] = None, - billing_information: Optional["_models.BillingInformation"] = None, - **kwargs: Any - ) -> None: - """ - :keyword reservation_id: Fully qualified id of the reservation being returned. - :paramtype reservation_id: str - :keyword quantity: Quantity to be returned. - :paramtype quantity: int - :keyword billing_refund_amount: Pricing information containing the amount and the currency - code. - :paramtype billing_refund_amount: ~azure.mgmt.reservations.models.Price - :keyword billing_information: billing information. - :paramtype billing_information: ~azure.mgmt.reservations.models.BillingInformation - """ - super().__init__(**kwargs) - self.reservation_id = reservation_id - self.quantity = quantity - self.billing_refund_amount = billing_refund_amount - self.billing_information = billing_information - - -class ReservationToPurchaseCalculateExchange(_serialization.Model): - """Reservation purchase details. - - :ivar properties: The request for reservation purchase. - :vartype properties: ~azure.mgmt.reservations.models.PurchaseRequest - :ivar billing_currency_total: Pricing information containing the amount and the currency code. - :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "PurchaseRequest"}, - "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, - } - - def __init__( - self, - *, - properties: Optional["_models.PurchaseRequest"] = None, - billing_currency_total: Optional["_models.Price"] = None, - **kwargs: Any - ) -> None: - """ - :keyword properties: The request for reservation purchase. - :paramtype properties: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword billing_currency_total: Pricing information containing the amount and the currency - code. - :paramtype billing_currency_total: ~azure.mgmt.reservations.models.Price - """ - super().__init__(**kwargs) - self.properties = properties - self.billing_currency_total = billing_currency_total - - -class ReservationToPurchaseExchange(_serialization.Model): - """Reservation purchase details. - - :ivar reservation_order_id: Fully qualified id of the reservationOrder being purchased. - :vartype reservation_order_id: str - :ivar reservation_id: Fully qualified id of the reservation being purchased. This value is only - guaranteed to be non-null if the purchase is successful. - :vartype reservation_id: str - :ivar properties: The request for reservation purchase. - :vartype properties: ~azure.mgmt.reservations.models.PurchaseRequest - :ivar billing_currency_total: Pricing information containing the amount and the currency code. - :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price - :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", - "Cancelled", and "Pending". - :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus - """ - - _attribute_map = { - "reservation_order_id": {"key": "reservationOrderId", "type": "str"}, - "reservation_id": {"key": "reservationId", "type": "str"}, - "properties": {"key": "properties", "type": "PurchaseRequest"}, - "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, - "status": {"key": "status", "type": "str"}, - } - - def __init__( - self, - *, - reservation_order_id: Optional[str] = None, - reservation_id: Optional[str] = None, - properties: Optional["_models.PurchaseRequest"] = None, - billing_currency_total: Optional["_models.Price"] = None, - status: Optional[Union[str, "_models.OperationStatus"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reservation_order_id: Fully qualified id of the reservationOrder being purchased. - :paramtype reservation_order_id: str - :keyword reservation_id: Fully qualified id of the reservation being purchased. This value is - only guaranteed to be non-null if the purchase is successful. - :paramtype reservation_id: str - :keyword properties: The request for reservation purchase. - :paramtype properties: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword billing_currency_total: Pricing information containing the amount and the currency - code. - :paramtype billing_currency_total: ~azure.mgmt.reservations.models.Price - :keyword status: Status of the individual operation. Known values are: "Succeeded", "Failed", - "Cancelled", and "Pending". - :paramtype status: str or ~azure.mgmt.reservations.models.OperationStatus - """ - super().__init__(**kwargs) - self.reservation_order_id = reservation_order_id - self.reservation_id = reservation_id - self.properties = properties - self.billing_currency_total = billing_currency_total - self.status = status - - -class ReservationToReturn(_serialization.Model): - """Reservation to return. - - :ivar reservation_id: Fully qualified identifier of the reservation being returned. - :vartype reservation_id: str - :ivar quantity: Quantity to be returned. Must be greater than zero. - :vartype quantity: int - """ - - _attribute_map = { - "reservation_id": {"key": "reservationId", "type": "str"}, - "quantity": {"key": "quantity", "type": "int"}, - } - - def __init__(self, *, reservation_id: Optional[str] = None, quantity: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword reservation_id: Fully qualified identifier of the reservation being returned. - :paramtype reservation_id: str - :keyword quantity: Quantity to be returned. Must be greater than zero. - :paramtype quantity: int - """ - super().__init__(**kwargs) - self.reservation_id = reservation_id - self.quantity = quantity - - -class ReservationToReturnForExchange(_serialization.Model): - """Reservation refund details. - - :ivar reservation_id: Fully qualified id of the reservation being returned. - :vartype reservation_id: str - :ivar quantity: Quantity to be returned. - :vartype quantity: int - :ivar billing_refund_amount: Pricing information containing the amount and the currency code. - :vartype billing_refund_amount: ~azure.mgmt.reservations.models.Price - :ivar billing_information: billing information. - :vartype billing_information: ~azure.mgmt.reservations.models.BillingInformation - :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", - "Cancelled", and "Pending". - :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus - """ - - _attribute_map = { - "reservation_id": {"key": "reservationId", "type": "str"}, - "quantity": {"key": "quantity", "type": "int"}, - "billing_refund_amount": {"key": "billingRefundAmount", "type": "Price"}, - "billing_information": {"key": "billingInformation", "type": "BillingInformation"}, - "status": {"key": "status", "type": "str"}, - } - - def __init__( - self, - *, - reservation_id: Optional[str] = None, - quantity: Optional[int] = None, - billing_refund_amount: Optional["_models.Price"] = None, - billing_information: Optional["_models.BillingInformation"] = None, - status: Optional[Union[str, "_models.OperationStatus"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reservation_id: Fully qualified id of the reservation being returned. - :paramtype reservation_id: str - :keyword quantity: Quantity to be returned. - :paramtype quantity: int - :keyword billing_refund_amount: Pricing information containing the amount and the currency - code. - :paramtype billing_refund_amount: ~azure.mgmt.reservations.models.Price - :keyword billing_information: billing information. - :paramtype billing_information: ~azure.mgmt.reservations.models.BillingInformation - :keyword status: Status of the individual operation. Known values are: "Succeeded", "Failed", - "Cancelled", and "Pending". - :paramtype status: str or ~azure.mgmt.reservations.models.OperationStatus - """ - super().__init__(**kwargs) - self.reservation_id = reservation_id - self.quantity = quantity - self.billing_refund_amount = billing_refund_amount - self.billing_information = billing_information - self.status = status - - -class ReservationUtilizationAggregates(_serialization.Model): - """The aggregate values of reservation utilization. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar grain: The grain of the aggregate. - :vartype grain: float - :ivar grain_unit: The grain unit of the aggregate. - :vartype grain_unit: str - :ivar value: The aggregate value. - :vartype value: float - :ivar value_unit: The aggregate value unit. - :vartype value_unit: str - """ - - _validation = { - "grain": {"readonly": True}, - "grain_unit": {"readonly": True}, - "value": {"readonly": True}, - "value_unit": {"readonly": True}, - } - - _attribute_map = { - "grain": {"key": "grain", "type": "float"}, - "grain_unit": {"key": "grainUnit", "type": "str"}, - "value": {"key": "value", "type": "float"}, - "value_unit": {"key": "valueUnit", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.grain = None - self.grain_unit = None - self.value = None - self.value_unit = None - - -class ResourceName(_serialization.Model): - """Resource name provided by the resource provider. Use this property for quotaRequest parameter. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Resource name. - :vartype value: str - :ivar localized_value: Resource display localized name. - :vartype localized_value: str - """ - - _validation = { - "localized_value": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "str"}, - "localized_value": {"key": "localizedValue", "type": "str"}, - } - - def __init__(self, *, value: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword value: Resource name. - :paramtype value: str - """ - super().__init__(**kwargs) - self.value = value - self.localized_value = None - - -class SavingsPlanPurchaseRequest(_serialization.Model): - """Request body for savings plan purchase. - - :ivar sku: The name of sku. - :vartype sku: ~azure.mgmt.reservations.models.SkuName - :ivar display_name: Friendly name of the savings plan. - :vartype display_name: str - :ivar billing_scope_id: Subscription that will be charged for purchasing reservation or savings - plan. - :vartype billing_scope_id: str - :ivar term: Represent savings plan term in ISO 8601 format. Known values are: "P1Y" and "P3Y". - :vartype term: str or ~azure.mgmt.reservations.models.SavingsPlanTerm - :ivar billing_plan: Represents the billing plan in ISO 8601 format. Required only for monthly - billing plans. "P1M" - :vartype billing_plan: str or ~azure.mgmt.reservations.models.BillingPlan - :ivar applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", and - "ManagementGroup". - :vartype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :ivar applied_scope_properties: Properties specific to applied scope type. Not required if not - applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType is - ManagementGroup. - :vartype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :ivar commitment: Commitment towards the benefit. - :vartype commitment: ~azure.mgmt.reservations.models.Commitment - """ - - _attribute_map = { - "sku": {"key": "sku", "type": "SkuName"}, - "display_name": {"key": "properties.displayName", "type": "str"}, - "billing_scope_id": {"key": "properties.billingScopeId", "type": "str"}, - "term": {"key": "properties.term", "type": "str"}, - "billing_plan": {"key": "properties.billingPlan", "type": "str"}, - "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, - "applied_scope_properties": {"key": "properties.appliedScopeProperties", "type": "AppliedScopeProperties"}, - "commitment": {"key": "properties.commitment", "type": "Commitment"}, - } - - def __init__( - self, - *, - sku: Optional["_models.SkuName"] = None, - display_name: Optional[str] = None, - billing_scope_id: Optional[str] = None, - term: Optional[Union[str, "_models.SavingsPlanTerm"]] = None, - billing_plan: Optional[Union[str, "_models.BillingPlan"]] = None, - applied_scope_type: Optional[Union[str, "_models.AppliedScopeType"]] = None, - applied_scope_properties: Optional["_models.AppliedScopeProperties"] = None, - commitment: Optional["_models.Commitment"] = None, - **kwargs: Any - ) -> None: - """ - :keyword sku: The name of sku. - :paramtype sku: ~azure.mgmt.reservations.models.SkuName - :keyword display_name: Friendly name of the savings plan. - :paramtype display_name: str - :keyword billing_scope_id: Subscription that will be charged for purchasing reservation or - savings plan. - :paramtype billing_scope_id: str - :keyword term: Represent savings plan term in ISO 8601 format. Known values are: "P1Y" and - "P3Y". - :paramtype term: str or ~azure.mgmt.reservations.models.SavingsPlanTerm - :keyword billing_plan: Represents the billing plan in ISO 8601 format. Required only for - monthly billing plans. "P1M" - :paramtype billing_plan: str or ~azure.mgmt.reservations.models.BillingPlan - :keyword applied_scope_type: Type of the Applied Scope. Known values are: "Single", "Shared", - and "ManagementGroup". - :paramtype applied_scope_type: str or ~azure.mgmt.reservations.models.AppliedScopeType - :keyword applied_scope_properties: Properties specific to applied scope type. Not required if - not applicable. Required and need to provide tenantId and managementGroupId if AppliedScopeType - is ManagementGroup. - :paramtype applied_scope_properties: ~azure.mgmt.reservations.models.AppliedScopeProperties - :keyword commitment: Commitment towards the benefit. - :paramtype commitment: ~azure.mgmt.reservations.models.Commitment - """ - super().__init__(**kwargs) - self.sku = sku - self.display_name = display_name - self.billing_scope_id = billing_scope_id - self.term = term - self.billing_plan = billing_plan - self.applied_scope_type = applied_scope_type - self.applied_scope_properties = applied_scope_properties - self.commitment = commitment - - -class SavingsPlanToPurchaseCalculateExchange(_serialization.Model): - """Savings plan purchase details. - - :ivar properties: Request body for savings plan purchase. - :vartype properties: ~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest - :ivar billing_currency_total: Pricing information containing the amount and the currency code. - :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price - """ - - _attribute_map = { - "properties": {"key": "properties", "type": "SavingsPlanPurchaseRequest"}, - "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, - } - - def __init__( - self, - *, - properties: Optional["_models.SavingsPlanPurchaseRequest"] = None, - billing_currency_total: Optional["_models.Price"] = None, - **kwargs: Any - ) -> None: - """ - :keyword properties: Request body for savings plan purchase. - :paramtype properties: ~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest - :keyword billing_currency_total: Pricing information containing the amount and the currency - code. - :paramtype billing_currency_total: ~azure.mgmt.reservations.models.Price - """ - super().__init__(**kwargs) - self.properties = properties - self.billing_currency_total = billing_currency_total - - -class SavingsPlanToPurchaseExchange(_serialization.Model): - """Savings plan purchase details. - - :ivar savings_plan_order_id: Fully qualified id of the savings plan order being purchased. - :vartype savings_plan_order_id: str - :ivar savings_plan_id: Fully qualified id of the savings plan being purchased. This value is - only guaranteed to be non-null if the purchase is successful. - :vartype savings_plan_id: str - :ivar properties: Request body for savings plan purchase. - :vartype properties: ~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest - :ivar billing_currency_total: Pricing information containing the amount and the currency code. - :vartype billing_currency_total: ~azure.mgmt.reservations.models.Price - :ivar status: Status of the individual operation. Known values are: "Succeeded", "Failed", - "Cancelled", and "Pending". - :vartype status: str or ~azure.mgmt.reservations.models.OperationStatus - """ - - _attribute_map = { - "savings_plan_order_id": {"key": "savingsPlanOrderId", "type": "str"}, - "savings_plan_id": {"key": "savingsPlanId", "type": "str"}, - "properties": {"key": "properties", "type": "SavingsPlanPurchaseRequest"}, - "billing_currency_total": {"key": "billingCurrencyTotal", "type": "Price"}, - "status": {"key": "status", "type": "str"}, - } - - def __init__( - self, - *, - savings_plan_order_id: Optional[str] = None, - savings_plan_id: Optional[str] = None, - properties: Optional["_models.SavingsPlanPurchaseRequest"] = None, - billing_currency_total: Optional["_models.Price"] = None, - status: Optional[Union[str, "_models.OperationStatus"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword savings_plan_order_id: Fully qualified id of the savings plan order being purchased. - :paramtype savings_plan_order_id: str - :keyword savings_plan_id: Fully qualified id of the savings plan being purchased. This value is - only guaranteed to be non-null if the purchase is successful. - :paramtype savings_plan_id: str - :keyword properties: Request body for savings plan purchase. - :paramtype properties: ~azure.mgmt.reservations.models.SavingsPlanPurchaseRequest - :keyword billing_currency_total: Pricing information containing the amount and the currency - code. - :paramtype billing_currency_total: ~azure.mgmt.reservations.models.Price - :keyword status: Status of the individual operation. Known values are: "Succeeded", "Failed", - "Cancelled", and "Pending". - :paramtype status: str or ~azure.mgmt.reservations.models.OperationStatus - """ - super().__init__(**kwargs) - self.savings_plan_order_id = savings_plan_order_id - self.savings_plan_id = savings_plan_id - self.properties = properties - self.billing_currency_total = billing_currency_total - self.status = status - - -class ScopeProperties(_serialization.Model): - """The scope and whether it is valid. - - :ivar scope: - :vartype scope: str - :ivar valid: - :vartype valid: bool - """ - - _attribute_map = { - "scope": {"key": "scope", "type": "str"}, - "valid": {"key": "valid", "type": "bool"}, - } - - def __init__(self, *, scope: Optional[str] = None, valid: Optional[bool] = None, **kwargs: Any) -> None: - """ - :keyword scope: - :paramtype scope: str - :keyword valid: - :paramtype valid: bool - """ - super().__init__(**kwargs) - self.scope = scope - self.valid = valid - - -class ServiceError(_serialization.Model): - """The API error details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message text. - :vartype message: str - :ivar details: The list of error details. - :vartype details: list[~azure.mgmt.reservations.models.ServiceErrorDetail] - """ - - _validation = { - "details": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "details": {"key": "details", "type": "[ServiceErrorDetail]"}, - } - - def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword code: The error code. - :paramtype code: str - :keyword message: The error message text. - :paramtype message: str - """ - super().__init__(**kwargs) - self.code = code - self.message = message - self.details = None - - -class ServiceErrorDetail(_serialization.Model): - """The error details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: The error code. - :vartype code: str - :ivar message: The error message. - :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: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - - -class SkuCapability(_serialization.Model): - """Capability of a sku. - - :ivar name: An invariant to describe the feature. - :vartype name: str - :ivar value: An invariant if the feature is measured by quantity. - :vartype value: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "value": {"key": "value", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: An invariant to describe the feature. - :paramtype name: str - :keyword value: An invariant if the feature is measured by quantity. - :paramtype value: str - """ - super().__init__(**kwargs) - self.name = name - self.value = value - - -class SkuName(_serialization.Model): - """The name of sku. - - :ivar name: - :vartype name: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: - :paramtype name: str - """ - super().__init__(**kwargs) - self.name = name - - -class SkuProperty(_serialization.Model): - """Property of a sku. - - :ivar name: An invariant to describe the feature. - :vartype name: str - :ivar value: An invariant if the feature is measured by quantity. - :vartype value: str - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "value": {"key": "value", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: An invariant to describe the feature. - :paramtype name: str - :keyword value: An invariant if the feature is measured by quantity. - :paramtype value: str - """ - super().__init__(**kwargs) - self.name = name - self.value = value - - -class SkuRestriction(_serialization.Model): - """Restriction of a sku. - - :ivar type: The type of restrictions. - :vartype type: str - :ivar values: The value of restrictions. If the restriction type is set to location. This would - be different locations where the sku is restricted. - :vartype values: list[str] - :ivar reason_code: The reason for restriction. - :vartype reason_code: str - """ - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "values": {"key": "values", "type": "[str]"}, - "reason_code": {"key": "reasonCode", "type": "str"}, - } - - def __init__( - self, - *, - type: Optional[str] = None, - values: Optional[List[str]] = None, - reason_code: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: The type of restrictions. - :paramtype type: str - :keyword values: The value of restrictions. If the restriction type is set to location. This - would be different locations where the sku is restricted. - :paramtype values: list[str] - :keyword reason_code: The reason for restriction. - :paramtype reason_code: str - """ - super().__init__(**kwargs) - self.type = type - self.values = values - self.reason_code = reason_code - - -class SplitRequest(_serialization.Model): - """The request for reservation split. - - :ivar quantities: List of the quantities in the new reservations to create. - :vartype quantities: list[int] - :ivar reservation_id: Resource id of the reservation to be split. Format of the resource id - should be - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :vartype reservation_id: str - """ - - _attribute_map = { - "quantities": {"key": "properties.quantities", "type": "[int]"}, - "reservation_id": {"key": "properties.reservationId", "type": "str"}, - } - - def __init__( - self, *, quantities: Optional[List[int]] = None, reservation_id: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword quantities: List of the quantities in the new reservations to create. - :paramtype quantities: list[int] - :keyword reservation_id: Resource id of the reservation to be split. Format of the resource id - should be - /providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}. - :paramtype reservation_id: str - """ - super().__init__(**kwargs) - self.quantities = quantities - self.reservation_id = reservation_id - - -class SubRequest(_serialization.Model): - """The sub-request submitted with the quota request. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar limit: Quota (resource limit). - :vartype limit: int - :ivar name: The resource name. - :vartype name: ~azure.mgmt.reservations.models.ResourceName - :ivar resource_type: Resource type for which the quota check was made. - :vartype resource_type: str - :ivar unit: The limit units, such as **count** and **bytes**. Use the unit field provided in - the response of the GET quota operation. - :vartype unit: str - :ivar provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", - "Succeeded", "Failed", and "InProgress". - :vartype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - :ivar message: User-friendly status message. - :vartype message: str - :ivar sub_request_id: Sub request ID for individual request. - :vartype sub_request_id: str - """ - - _validation = { - "limit": {"readonly": True}, - "resource_type": {"readonly": True}, - "message": {"readonly": True}, - "sub_request_id": {"readonly": True}, - } - - _attribute_map = { - "limit": {"key": "limit", "type": "int"}, - "name": {"key": "name", "type": "ResourceName"}, - "resource_type": {"key": "resourceType", "type": "str"}, - "unit": {"key": "unit", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "sub_request_id": {"key": "subRequestId", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional["_models.ResourceName"] = None, - unit: Optional[str] = None, - provisioning_state: Optional[Union[str, "_models.QuotaRequestState"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: The resource name. - :paramtype name: ~azure.mgmt.reservations.models.ResourceName - :keyword unit: The limit units, such as **count** and **bytes**. Use the unit field provided in - the response of the GET quota operation. - :paramtype unit: str - :keyword provisioning_state: The quota request status. Known values are: "Accepted", "Invalid", - "Succeeded", "Failed", and "InProgress". - :paramtype provisioning_state: str or ~azure.mgmt.reservations.models.QuotaRequestState - """ - super().__init__(**kwargs) - self.limit = None - self.name = name - self.resource_type = None - self.unit = unit - self.provisioning_state = provisioning_state - self.message = None - self.sub_request_id = None - - -class SubscriptionScopeProperties(_serialization.Model): - """The scopes checked by the available scope api. - - :ivar scopes: - :vartype scopes: list[~azure.mgmt.reservations.models.ScopeProperties] - """ - - _attribute_map = { - "scopes": {"key": "scopes", "type": "[ScopeProperties]"}, - } - - def __init__(self, *, scopes: Optional[List["_models.ScopeProperties"]] = None, **kwargs: Any) -> None: - """ - :keyword scopes: - :paramtype scopes: list[~azure.mgmt.reservations.models.ScopeProperties] - """ - super().__init__(**kwargs) - self.scopes = scopes - - -class SystemData(_serialization.Model): - """Metadata pertaining to creation and last modification of the resource. - - :ivar created_by: The identity that created the resource. - :vartype created_by: str - :ivar created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.mgmt.reservations.models.CreatedByType - :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime - :ivar last_modified_by: The identity that last modified the resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of identity that last modified the resource. Known values - are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or ~azure.mgmt.reservations.models.CreatedByType - :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime - """ - - _attribute_map = { - "created_by": {"key": "createdBy", "type": "str"}, - "created_by_type": {"key": "createdByType", "type": "str"}, - "created_at": {"key": "createdAt", "type": "iso-8601"}, - "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, - "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, - "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, - } - - 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, - **kwargs: Any - ) -> None: - """ - :keyword created_by: The identity that created the resource. - :paramtype created_by: str - :keyword created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :paramtype created_by_type: str or ~azure.mgmt.reservations.models.CreatedByType - :keyword created_at: The timestamp of resource creation (UTC). - :paramtype created_at: ~datetime.datetime - :keyword last_modified_by: The identity that last modified the resource. - :paramtype last_modified_by: str - :keyword last_modified_by_type: The type of identity that last modified the resource. Known - values are: "User", "Application", "ManagedIdentity", and "Key". - :paramtype last_modified_by_type: str or ~azure.mgmt.reservations.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__(**kwargs) - self.created_by = created_by - self.created_by_type = created_by_type - self.created_at = created_at - self.last_modified_by = last_modified_by - self.last_modified_by_type = last_modified_by_type - self.last_modified_at = last_modified_at diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/models/_patch.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py index d6b78b37947f..95366886f02a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/__init__.py @@ -2,36 +2,41 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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 ._reservation_operations import ReservationOperations -from ._azure_reservation_api_operations import AzureReservationAPIOperationsMixin -from ._reservation_order_operations import ReservationOrderOperations -from ._operation_operations import OperationOperations -from ._calculate_refund_operations import CalculateRefundOperations -from ._return_operations_operations import ReturnOperations -from ._calculate_exchange_operations import CalculateExchangeOperations -from ._exchange_operations import ExchangeOperations -from ._quota_operations import QuotaOperations -from ._quota_request_status_operations import QuotaRequestStatusOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import QuotaRequestStatusOperations # type: ignore +from ._operations import OperationOperations # type: ignore +from ._operations import QuotaOperations # type: ignore +from ._operations import ReservationOperations # type: ignore +from ._operations import ReservationOrderOperations # type: ignore +from ._operations import CalculateRefundOperations # type: ignore +from ._operations import ReturnOperations # type: ignore +from ._operations import CalculateExchangeOperations # type: ignore +from ._operations import ExchangeOperations # type: ignore +from ._operations import _ReservationsMgmtClientOperationsMixin # type: ignore # pylint: disable=unused-import 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__ = [ + "QuotaRequestStatusOperations", + "OperationOperations", + "QuotaOperations", "ReservationOperations", - "AzureReservationAPIOperationsMixin", "ReservationOrderOperations", - "OperationOperations", "CalculateRefundOperations", "ReturnOperations", "CalculateExchangeOperations", "ExchangeOperations", - "QuotaOperations", - "QuotaRequestStatusOperations", ] -__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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py deleted file mode 100644 index 81344fc6ab41..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_azure_reservation_api_operations.py +++ /dev/null @@ -1,295 +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 - -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 AzureReservationAPIMixinABC, _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_catalog_request( - subscription_id: str, - *, - reserved_resource_type: Optional[str] = None, - location: Optional[str] = None, - publisher_id: Optional[str] = None, - offer_id: Optional[str] = None, - plan_id: Optional[str] = None, - filter: Optional[str] = None, - skip: Optional[float] = None, - take: Optional[float] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if reserved_resource_type is not None: - _params["reservedResourceType"] = _SERIALIZER.query("reserved_resource_type", reserved_resource_type, "str") - if location is not None: - _params["location"] = _SERIALIZER.query("location", location, "str") - if publisher_id is not None: - _params["publisherId"] = _SERIALIZER.query("publisher_id", publisher_id, "str") - if offer_id is not None: - _params["offerId"] = _SERIALIZER.query("offer_id", offer_id, "str") - if plan_id is not None: - _params["planId"] = _SERIALIZER.query("plan_id", plan_id, "str") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if skip is not None: - _params["$skip"] = _SERIALIZER.query("skip", skip, "float") - if take is not None: - _params["$take"] = _SERIALIZER.query("take", take, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_applied_reservation_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_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 AzureReservationAPIOperationsMixin(AzureReservationAPIMixinABC): - @distributed_trace - def get_catalog( - self, - subscription_id: str, - reserved_resource_type: Optional[str] = None, - location: Optional[str] = None, - publisher_id: Optional[str] = None, - offer_id: Optional[str] = None, - plan_id: Optional[str] = None, - filter: Optional[str] = None, - skip: Optional[float] = None, - take: Optional[float] = None, - **kwargs: Any - ) -> Iterable["_models.Catalog"]: - """Get the regions and skus that are available for RI purchase for the specified Azure - subscription. - - Get the regions and skus that are available for RI purchase for the specified Azure - subscription. - - :param subscription_id: Id of the subscription. Required. - :type subscription_id: str - :param reserved_resource_type: The type of the resource for which the skus should be provided. - Default value is None. - :type reserved_resource_type: str - :param location: Filters the skus based on the location specified in this parameter. This can - be an Azure region or global. Default value is None. - :type location: str - :param publisher_id: Publisher id used to get the third party products. Default value is None. - :type publisher_id: str - :param offer_id: Offer id used to get the third party products. Default value is None. - :type offer_id: str - :param plan_id: Plan id used to get the third party products. Default value is None. - :type plan_id: str - :param filter: May be used to filter by Catalog properties. The filter supports 'eq', 'or', and - 'and'. Default value is None. - :type filter: str - :param skip: The number of reservations to skip from the list before returning results. Default - value is None. - :type skip: float - :param take: To number of reservations to return. Default value is None. - :type take: float - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either Catalog or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.Catalog] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.CatalogsResult] = 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_get_catalog_request( - subscription_id=subscription_id, - reserved_resource_type=reserved_resource_type, - location=location, - publisher_id=publisher_id, - offer_id=offer_id, - plan_id=plan_id, - filter=filter, - skip=skip, - take=take, - api_version=api_version, - template_url=self.get_catalog.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - 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("CatalogsResult", 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - get_catalog.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs"} - - @distributed_trace - def get_applied_reservation_list(self, subscription_id: str, **kwargs: Any) -> _models.AppliedReservations: - """Get list of applicable ``Reservation``\ s. - - Get applicable ``Reservation``\ s that are applied to this subscription or a resource group - under this subscription. - - :param subscription_id: Id of the subscription. Required. - :type subscription_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AppliedReservations or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.AppliedReservations - :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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.AppliedReservations] = kwargs.pop("cls", None) - - request = build_get_applied_reservation_list_request( - subscription_id=subscription_id, - api_version=api_version, - template_url=self.get_applied_reservation_list.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("AppliedReservations", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get_applied_reservation_list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py deleted file mode 100644 index a27305decbb0..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_exchange_operations.py +++ /dev/null @@ -1,281 +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, Optional, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import AzureReservationAPIMixinABC, _convert_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, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_post_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/calculateExchange") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class CalculateExchangeOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`calculate_exchange` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - def _post_initial( - self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any - ) -> Optional[_models.CalculateExchangeOperationResultResponse]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.CalculateExchangeOperationResultResponse]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CalculateExchangeRequest") - - request = build_post_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._post_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("CalculateExchangeOperationResultResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} - - @overload - def begin_post( - self, body: _models.CalculateExchangeRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: - """Calculates the refund amounts and price of the new purchases. - - Calculates price for exchanging ``Reservations`` if there are no policy errors. - - :param body: Request containing purchases and refunds that need to be executed. Required. - :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CalculateExchangeOperationResultResponse - or the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_post( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: - """Calculates the refund amounts and price of the new purchases. - - Calculates price for exchanging ``Reservations`` if there are no policy errors. - - :param body: Request containing purchases and refunds that need to be executed. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CalculateExchangeOperationResultResponse - or the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_post( - self, body: Union[_models.CalculateExchangeRequest, IO], **kwargs: Any - ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: - """Calculates the refund amounts and price of the new purchases. - - Calculates price for exchanging ``Reservations`` if there are no policy errors. - - :param body: Request containing purchases and refunds that need to be executed. Is either a - CalculateExchangeRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CalculateExchangeOperationResultResponse - or the result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CalculateExchangeOperationResultResponse] = 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._post_initial( - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CalculateExchangeOperationResultResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post.metadata = {"url": "/providers/Microsoft.Capacity/calculateExchange"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py deleted file mode 100644 index 720fb131719e..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_calculate_refund_operations.py +++ /dev/null @@ -1,212 +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, Optional, TypeVar, Union, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import AzureReservationAPIMixinABC, _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_post_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/calculateRefund" - ) - 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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class CalculateRefundOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`calculate_refund` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def post( - self, - reservation_order_id: str, - body: _models.CalculateRefundRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.CalculateRefundResponse: - """Calculate the refund amount of a reservation order. - - Calculate price for returning ``Reservations`` if there are no policy errors. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculating refund of a reservation. Required. - :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculateRefundResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def post( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CalculateRefundResponse: - """Calculate the refund amount of a reservation order. - - Calculate price for returning ``Reservations`` if there are no policy errors. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculating refund of a reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculateRefundResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def post( - self, reservation_order_id: str, body: Union[_models.CalculateRefundRequest, IO], **kwargs: Any - ) -> _models.CalculateRefundResponse: - """Calculate the refund amount of a reservation order. - - Calculate price for returning ``Reservations`` if there are no policy errors. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculating refund of a reservation. Is either a - CalculateRefundRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculateRefundResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CalculateRefundResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "CalculateRefundRequest") - - request = build_post_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.post.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CalculateRefundResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/calculateRefund"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py deleted file mode 100644 index 7dc422c650d7..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_exchange_operations.py +++ /dev/null @@ -1,281 +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, Optional, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import AzureReservationAPIMixinABC, _convert_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, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_post_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/exchange") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class ExchangeOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`exchange` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - def _post_initial( - self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any - ) -> Optional[_models.ExchangeOperationResultResponse]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ExchangeOperationResultResponse]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ExchangeRequest") - - request = build_post_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._post_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ExchangeOperationResultResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} - - @overload - def begin_post( - self, body: _models.ExchangeRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.ExchangeOperationResultResponse]: - """Exchange Reservation(s). - - Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - - :param body: Request containing the refunds and purchases that need to be executed. Required. - :type body: ~azure.mgmt.reservations.models.ExchangeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ExchangeOperationResultResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_post( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.ExchangeOperationResultResponse]: - """Exchange Reservation(s). - - Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - - :param body: Request containing the refunds and purchases that need to be executed. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ExchangeOperationResultResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_post( - self, body: Union[_models.ExchangeRequest, IO], **kwargs: Any - ) -> LROPoller[_models.ExchangeOperationResultResponse]: - """Exchange Reservation(s). - - Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. - - :param body: Request containing the refunds and purchases that need to be executed. Is either a - ExchangeRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.ExchangeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ExchangeOperationResultResponse or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ExchangeOperationResultResponse] = 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._post_initial( - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ExchangeOperationResultResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post.metadata = {"url": "/providers/Microsoft.Capacity/exchange"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py deleted file mode 100644 index bf3b599edaa0..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operation_operations.py +++ /dev/null @@ -1,149 +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 - -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 AzureReservationAPIMixinABC, _convert_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, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/operations") - - # 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 OperationOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`operation` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.OperationResponse"]: - """Get operations. - - List all the operations. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationResponse or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.OperationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.OperationList] = 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( - 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: - request = HttpRequest("GET", next_link) - 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("OperationList", 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.Error, 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.Capacity/operations"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operations.py new file mode 100644 index 000000000000..eefdf09c99a8 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_operations.py @@ -0,0 +1,5047 @@ +# 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. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload + +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.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 .._configuration import ReservationsMgmtClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Deserializer, Serializer +from .._utils.utils import ClientMixinABC +from .._validation import api_version_validation + +T = TypeVar("T") +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_quota_request_status_get_request( + subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "id": _SERIALIZER.url("id", id, "str"), + } + + _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_quota_request_status_list_request( + subscription_id: str, + provider_id: str, + location: 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", "2020-10-25")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + } + + _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_operation_list_request(**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", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/operations" + + # 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_quota_get_request( + subscription_id: str, provider_id: str, location: str, resource_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", "2020-10-25")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _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_quota_create_or_update_request( + subscription_id: str, provider_id: str, location: str, resource_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", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _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_quota_update_request( + subscription_id: str, provider_id: str, location: str, resource_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", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), + } + + _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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_quota_list_request(subscription_id: str, provider_id: str, location: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), + "location": _SERIALIZER.url("location", location, "str"), + } + + _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_reservation_get_request( + reservation_order_id: str, reservation_id: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" + 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") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_update_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" + 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") + + # 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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_list_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations" + 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") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_available_scopes_request( # pylint: disable=name-too-long + reservation_order_id: str, reservation_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes" + 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") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_archive_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/archive" + 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") + + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) + + +def build_reservation_unarchive_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/unarchive" + 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") + + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) + + +def build_reservation_list_revisions_request( + reservation_order_id: str, reservation_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions" + 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") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_split_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split" + 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") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_merge_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge" + 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") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_list_all_request( + *, + filter: Optional[str] = None, + orderby: Optional[str] = None, + refresh_summary: Optional[str] = None, + skiptoken: Optional[float] = None, + selected_state: Optional[str] = None, + take: Optional[float] = 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", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservations" + + # 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 orderby is not None: + _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") + if refresh_summary is not None: + _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "float") + if selected_state is not None: + _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") + if take is not None: + _params["take"] = _SERIALIZER.query("take", take, "float") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_order_get_request( + reservation_order_id: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}" + 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") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_order_purchase_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}" + 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") + + # 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_reservation_order_list_request(**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", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders" + + # 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_reservation_order_change_directory_request( # pylint: disable=name-too-long + reservation_order_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory" + 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") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservation_order_calculate_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/calculatePrice" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_calculate_refund_post_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/calculateRefund" + 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") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_return_operations_post_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return" + 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") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_calculate_exchange_post_request(**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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/calculateExchange" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_exchange_post_request(**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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/providers/Microsoft.Capacity/exchange" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_mgmt_get_catalog_request( # pylint: disable=name-too-long + subscription_id: str, + *, + reserved_resource_type: Optional[str] = None, + location: Optional[str] = None, + publisher_id: Optional[str] = None, + offer_id: Optional[str] = None, + plan_id: Optional[str] = None, + filter: Optional[str] = None, + skip: Optional[float] = None, + take: Optional[float] = 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", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/catalogs" + 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 reserved_resource_type is not None: + _params["reservedResourceType"] = _SERIALIZER.query("reserved_resource_type", reserved_resource_type, "str") + if location is not None: + _params["location"] = _SERIALIZER.query("location", location, "str") + if publisher_id is not None: + _params["publisherId"] = _SERIALIZER.query("publisher_id", publisher_id, "str") + if offer_id is not None: + _params["offerId"] = _SERIALIZER.query("offer_id", offer_id, "str") + if plan_id is not None: + _params["planId"] = _SERIALIZER.query("plan_id", plan_id, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if skip is not None: + _params["$skip"] = _SERIALIZER.query("skip", skip, "float") + if take is not None: + _params["$take"] = _SERIALIZER.query("take", take, "float") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_reservations_mgmt_get_applied_reservation_list_request( # pylint: disable=name-too-long + subscription_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", "2022-11-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/appliedReservations" + 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") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class QuotaRequestStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`quota_request_status` 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: ReservationsMgmtClientConfiguration = 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, subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any + ) -> _models.QuotaRequestDetails: + """For the specified Azure region (location), get the details and status of the quota request by + the quota request ID for the resources of the resource provider. The PUT request for the quota + (service limit) returns a response with the requestId parameter. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param id: Quota Request ID. Required. + :type id: str + :return: QuotaRequestDetails. The QuotaRequestDetails is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.QuotaRequestDetails + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[_models.QuotaRequestDetails] = kwargs.pop("cls", None) + + _request = build_quota_request_status_get_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + id=id, + api_version=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.ExceptionResponse, + 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.QuotaRequestDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + subscription_id: str, + provider_id: str, + location: str, + *, + filter: Optional[str] = None, + top: Optional[int] = None, + skiptoken: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.QuotaRequestDetails"]: + """For the specified Azure region (location), subscription, and resource provider, get the history + of the quota requests for the past year. To select specific quota requests, use the oData + filter. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :keyword filter: | Field | Supported operators | + |---------------------|------------------------| + |requestSubmitTime | ge, le, eq, gt, lt |. Default value is None. + :paramtype filter: str + :keyword top: Number of records to return. 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 includes + 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 QuotaRequestDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[List[_models.QuotaRequestDetails]] = 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_quota_request_status_list_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + filter=filter, + top=top, + skiptoken=skiptoken, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.QuotaRequestDetails], + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class OperationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`operation` 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: ReservationsMgmtClientConfiguration = 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.OperationResponse"]: + """Get operations. + + List all the operations. + + :return: An iterator like instance of OperationResponse + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.OperationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.OperationResponse]] = 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_operation_list_request( + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.OperationResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class QuotaOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`quota` 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: ReservationsMgmtClientConfiguration = 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, subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any + ) -> _models.CurrentQuotaLimitBase: + """Get the current quota (service limit) and usage of a resource. You can use the response from + the GET operation to submit quota update request. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :return: CurrentQuotaLimitBase. The CurrentQuotaLimitBase is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[_models.CurrentQuotaLimitBase] = kwargs.pop("cls", None) + + _request = build_quota_get_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + api_version=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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CurrentQuotaLimitBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + def _create_or_update_initial( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(create_quota_request, (IOBase, bytes)): + _content = create_quota_request + else: + _content = json.dumps(create_quota_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_quota_create_or_update_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + api_version=api_version, + content_type=content_type, + 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 = 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, 201]: + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Required. + :type create_quota_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Create or update the quota (service limits) of a resource to the requested value. + Steps: + + 1. Make the Get request to get the quota information for specific resource. + 2. To increase the quota, update the limit field in the response from Get request to new value. + 3. Submit the JSON to the quota request API to update the quota. + The Create quota request may be constructed as follows. The PUT operation can be used to update + the quota. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Quota requests payload. Is one of the following types: + CurrentQuotaLimitBase, JSON, IO[bytes] Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or JSON or + IO[bytes] + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CurrentQuotaLimitBase] = 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._create_or_update_initial( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + create_quota_request=create_quota_request, + api_version=api_version, + content_type=content_type, + 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.CurrentQuotaLimitBase, 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.CurrentQuotaLimitBase].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CurrentQuotaLimitBase]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(create_quota_request, (IOBase, bytes)): + _content = create_quota_request + else: + _content = json.dumps(create_quota_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_quota_update_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + api_version=api_version, + content_type=content_type, + 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 = 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, 201]: + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 201: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: _models.CurrentQuotaLimitBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Required. + :type create_quota_request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + subscription_id: str, + provider_id: str, + location: str, + resource_name: str, + create_quota_request: Union[_models.CurrentQuotaLimitBase, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.CurrentQuotaLimitBase]: + """Update the quota (service limits) of this resource to the requested value. • To get the quota + information for specific resource, send a GET request. • To increase the quota, update the + limit field from the GET response to a new value. • To update the quota value, submit the JSON + response to the quota request API to update the quota. • To update the quota. use the PATCH + operation. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :param resource_name: The resource name for a resource provider, such as SKU name for + Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. + Required. + :type resource_name: str + :param create_quota_request: Payload for the quota request. Is one of the following types: + CurrentQuotaLimitBase, JSON, IO[bytes] Required. + :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or JSON or + IO[bytes] + :return: An instance of LROPoller that returns CurrentQuotaLimitBase. The CurrentQuotaLimitBase + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2020-10-25")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CurrentQuotaLimitBase] = 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._update_initial( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + resource_name=resource_name, + create_quota_request=create_quota_request, + api_version=api_version, + content_type=content_type, + 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.CurrentQuotaLimitBase, 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.CurrentQuotaLimitBase].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CurrentQuotaLimitBase]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list( + self, subscription_id: str, provider_id: str, location: str, **kwargs: Any + ) -> ItemPaged["_models.CurrentQuotaLimitBase"]: + """Gets a list of current quotas (service limits) and usage for all resources. The response from + the list quota operation can be leveraged to request quota updates. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :param provider_id: Azure resource provider ID. Required. + :type provider_id: str + :param location: Azure region. Required. + :type location: str + :return: An iterator like instance of CurrentQuotaLimitBase + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) + cls: ClsType[List[_models.CurrentQuotaLimitBase]] = 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_quota_list_request( + subscription_id=subscription_id, + provider_id=provider_id, + location=location, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.CurrentQuotaLimitBase], + 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.ExceptionResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class ReservationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`reservation` 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: ReservationsMgmtClientConfiguration = 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, reservation_order_id: str, reservation_id: str, *, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationResponse: + """Get ``Reservation`` details. + + Get specific ``Reservation`` details. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :keyword expand: Supported value of this query is renewProperties. Default value is None. + :paramtype expand: str + :return: ReservationResponse. The ReservationResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ReservationResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[_models.ReservationResponse] = kwargs.pop("cls", None) + + _request = build_reservation_get_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + expand=expand, + api_version=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.Error, + 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.ReservationResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _update_initial( + self, + reservation_order_id: str, + reservation_id: str, + parameters: Union[_models.Patch, JSON, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = 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_reservation_update_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: _models.Patch, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Required. + :type parameters: ~azure.mgmt.reservations.models.Patch + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationResponse. The ReservationResponse is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationResponse. The ReservationResponse is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationResponse. The ReservationResponse is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + reservation_order_id: str, + reservation_id: str, + parameters: Union[_models.Patch, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.ReservationResponse]: + """Updates a ``Reservation``. + + Updates the applied scopes of the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param parameters: Information needed to patch a reservation item. Is one of the following + types: Patch, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.reservations.models.Patch or JSON or IO[bytes] + :return: An instance of LROPoller that returns ReservationResponse. The ReservationResponse is + compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReservationResponse] = 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._update_initial( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + 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.ReservationResponse, 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.ReservationResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ReservationResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list(self, reservation_order_id: str, **kwargs: Any) -> ItemPaged["_models.ReservationResponse"]: + """Get ``Reservation``s in a given reservation Order. + + List ``Reservation``s within a single ``ReservationOrder``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :return: An iterator like instance of ReservationResponse + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationResponse]] = 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_list_request( + reservation_order_id=reservation_order_id, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + def _available_scopes_initial( + self, + reservation_order_id: str, + reservation_id: str, + body: Union[_models.AvailableScopeRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_available_scopes_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=api_version, + content_type=content_type, + 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 = 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]: + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: _models.AvailableScopeRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Required. + :type body: 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: An instance of LROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_available_scopes( + self, + reservation_order_id: str, + reservation_id: str, + body: Union[_models.AvailableScopeRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.AvailableScopeProperties]: + """Get Available Scopes for ``Reservation``. + + Check whether the scopes from request is valid for ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :param body: Scopes to be checked for eligibility. Is one of the following types: + AvailableScopeRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest or JSON or IO[bytes] + :return: An instance of LROPoller that returns AvailableScopeProperties. The + AvailableScopeProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AvailableScopeProperties] = 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._available_scopes_initial( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + body=body, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + 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_headers = {} + response = pipeline_response.http_response + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + deserialized = _deserialize(_models.AvailableScopeProperties, response.json()) + if cls: + return cls(pipeline_response, deserialized, response_headers) # 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.AvailableScopeProperties].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.AvailableScopeProperties]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def archive( # pylint: disable=inconsistent-return-statements + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> None: + """Archive a ``Reservation``. + + Archiving a ``Reservation`` moves it to ``Archived`` state. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_reservation_archive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def unarchive( # pylint: disable=inconsistent-return-statements + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> None: + """Unarchive a ``Reservation``. + + Restores a ``Reservation`` to the state it was before archiving. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_reservation_unarchive_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_revisions( + self, reservation_order_id: str, reservation_id: str, **kwargs: Any + ) -> ItemPaged["_models.ReservationResponse"]: + """Get ``Reservation`` revisions. + + List of all the revisions for the ``Reservation``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param reservation_id: Id of the reservation item. Required. + :type reservation_id: str + :return: An iterator like instance of ReservationResponse + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationResponse]] = 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_list_revisions_request( + reservation_order_id=reservation_order_id, + reservation_id=reservation_id, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + def _split_initial( + self, reservation_order_id: str, body: Union[_models.SplitRequest, JSON, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_split_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_split( + self, + reservation_order_id: str, + body: _models.SplitRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: ~azure.mgmt.reservations.models.SplitRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_split( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_split( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_split( + self, reservation_order_id: str, body: Union[_models.SplitRequest, JSON, IO[bytes]], **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Split the ``Reservation``. + + Split a ``Reservation`` into two ``Reservation``s with specified quantity distribution. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to Split a reservation item. Is one of the following types: + SplitRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.SplitRequest or JSON or IO[bytes] + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.ReservationResponse]] = 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._split_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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(List[_models.ReservationResponse], 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[List[_models.ReservationResponse]].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[List[_models.ReservationResponse]]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _merge_initial( + self, reservation_order_id: str, body: Union[_models.MergeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_merge_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_merge( + self, + reservation_order_id: str, + body: _models.MergeRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: ~azure.mgmt.reservations.models.MergeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_merge( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_merge( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_merge( + self, reservation_order_id: str, body: Union[_models.MergeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> LROPoller[List[_models.ReservationResponse]]: + """Merges two ``Reservation``s. + + Merge the specified ``Reservation``s into a new ``Reservation``. The two ``Reservation``s being + merged must have same properties. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for commercial request for a reservation. Is one of the + following types: MergeRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.MergeRequest or JSON or IO[bytes] + :return: An instance of LROPoller that returns list of ReservationResponse + :rtype: + ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.ReservationResponse]] = 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._merge_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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(List[_models.ReservationResponse], 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[List[_models.ReservationResponse]].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[List[_models.ReservationResponse]]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list_all( + self, + *, + filter: Optional[str] = None, + orderby: Optional[str] = None, + refresh_summary: Optional[str] = None, + skiptoken: Optional[float] = None, + selected_state: Optional[str] = None, + take: Optional[float] = None, + **kwargs: Any + ) -> ItemPaged["_models.ReservationResponse"]: + """List the reservations and the roll up counts of reservations group by provisioning states that + the user has access to in the current tenant. + + :keyword filter: May be used to filter by reservation properties. The filter supports 'eq', + 'or', and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation + properties include sku/name, properties/{appliedScopeType, archived, displayName, + displayProvisioningState, effectiveDateTime, expiryDate, expiryDateTime, provisioningState, + quantity, renew, reservedResourceType, term, userFriendlyAppliedScopeType, + userFriendlyRenewState}. Default value is None. + :paramtype filter: str + :keyword orderby: May be used to sort order by reservation properties. Default value is None. + :paramtype orderby: str + :keyword refresh_summary: To indicate whether to refresh the roll up counts of the reservations + group by provisioning states. Default value is None. + :paramtype refresh_summary: str + :keyword skiptoken: The number of reservations to skip from the list before returning results. + Default value is None. + :paramtype skiptoken: float + :keyword selected_state: The selected provisioning state. Default value is None. + :paramtype selected_state: str + :keyword take: To number of reservations to return. Default value is None. + :paramtype take: float + :return: An iterator like instance of ReservationResponse + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationResponse]] = 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_list_all_request( + filter=filter, + orderby=orderby, + refresh_summary=refresh_summary, + skiptoken=skiptoken, + selected_state=selected_state, + take=take, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationResponse], + 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 ReservationOrderOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`reservation_order` 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: ReservationsMgmtClientConfiguration = 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, reservation_order_id: str, *, expand: Optional[str] = None, **kwargs: Any + ) -> _models.ReservationOrderResponse: + """Get a specific ``ReservationOrder``. + + Get the details of the ``ReservationOrder``. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :keyword expand: May be used to expand the planInformation. Default value is None. + :paramtype expand: str + :return: ReservationOrderResponse. The ReservationOrderResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.reservations.models.ReservationOrderResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[_models.ReservationOrderResponse] = kwargs.pop("cls", None) + + _request = build_reservation_order_get_request( + reservation_order_id=reservation_order_id, + expand=expand, + api_version=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.Error, + 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.ReservationOrderResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _purchase_initial( + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, JSON, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_order_purchase_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_purchase( + self, + reservation_order_id: str, + body: _models.PurchaseRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_purchase( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_purchase( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_purchase( + self, reservation_order_id: str, body: Union[_models.PurchaseRequest, JSON, IO[bytes]], **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Purchase ``ReservationOrder``. + + Purchase ``ReservationOrder`` and create resource under the specified URI. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculate or purchase reservation. Is one of the following + types: PurchaseRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or JSON or IO[bytes] + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReservationOrderResponse] = 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._purchase_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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.ReservationOrderResponse, 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.ReservationOrderResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ReservationOrderResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.ReservationOrderResponse"]: + """Get all ``ReservationOrder``s. + + List of all the ``ReservationOrder``s that the user has access to in the current tenant. + + :return: An iterator like instance of ReservationOrderResponse + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.ReservationOrderResponse]] = 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_order_list_request( + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.ReservationOrderResponse], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def change_directory( + self, + reservation_order_id: str, + body: _models.ChangeDirectoryRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def change_directory( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def change_directory( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def change_directory( + self, reservation_order_id: str, body: Union[_models.ChangeDirectoryRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.ChangeDirectoryResponse: + """Change directory of ``ReservationOrder``. + + Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified + tenant id. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed to change directory of reservation order. Is one of the + following types: ChangeDirectoryRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest or JSON or IO[bytes] + :return: ChangeDirectoryResponse. The ChangeDirectoryResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ChangeDirectoryResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_order_change_directory_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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]: + 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.Error, + 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.ChangeDirectoryResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def calculate( + self, body: _models.PurchaseRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def calculate( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def calculate( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Required. + :type body: 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: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def calculate( + self, body: Union[_models.PurchaseRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CalculatePriceResponse: + """Calculate price for a ``ReservationOrder``. + + Calculate price for placing a ``ReservationOrder``. + + :param body: The request body. Is one of the following types: PurchaseRequest, JSON, IO[bytes] + Required. + :type body: ~azure.mgmt.reservations.models.PurchaseRequest or JSON or IO[bytes] + :return: CalculatePriceResponse. The CalculatePriceResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CalculatePriceResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_reservation_order_calculate_request( + api_version=api_version, + content_type=content_type, + 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]: + 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.Error, + 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.CalculatePriceResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CalculateRefundOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`calculate_refund` 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: ReservationsMgmtClientConfiguration = 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") + + @overload + def post( + self, + reservation_order_id: str, + body: _models.CalculateRefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def post( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def post( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def post( + self, reservation_order_id: str, body: Union[_models.CalculateRefundRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CalculateRefundResponse: + """Calculate the refund amount of a reservation order. + + Calculate price for returning ``Reservations`` if there are no policy errors. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for calculating refund of a reservation. Is one of the + following types: CalculateRefundRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.CalculateRefundRequest or JSON or IO[bytes] + :return: CalculateRefundResponse. The CalculateRefundResponse is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.CalculateRefundResponse + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CalculateRefundResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_calculate_refund_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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]: + 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.Error, + 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.CalculateRefundResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ReturnOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`return_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: ReservationsMgmtClientConfiguration = 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") + + def _post_initial( + self, reservation_order_id: str, body: Union[_models.RefundRequest, JSON, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_return_operations_post_request( + reservation_order_id=reservation_order_id, + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + 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")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_post( + self, + reservation_order_id: str, + body: _models.RefundRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, reservation_order_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, reservation_order_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_post( + self, reservation_order_id: str, body: Union[_models.RefundRequest, JSON, IO[bytes]], **kwargs: Any + ) -> LROPoller[_models.ReservationOrderResponse]: + """Return a reservation. + + Return a reservation and get refund information. + + :param reservation_order_id: Order Id of the reservation. Required. + :type reservation_order_id: str + :param body: Information needed for returning reservation. Is one of the following types: + RefundRequest, JSON, IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.RefundRequest or JSON or IO[bytes] + :return: An instance of LROPoller that returns ReservationOrderResponse. The + ReservationOrderResponse is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ReservationOrderResponse] = 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._post_initial( + reservation_order_id=reservation_order_id, + body=body, + api_version=api_version, + content_type=content_type, + 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.ReservationOrderResponse, 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.ReservationOrderResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ReservationOrderResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class CalculateExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`calculate_exchange` 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: ReservationsMgmtClientConfiguration = 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") + + def _post_initial( + self, body: Union[_models.CalculateExchangeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_calculate_exchange_post_request( + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_post( + self, body: _models.CalculateExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CalculateExchangeOperationResultResponse. The + CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns CalculateExchangeOperationResultResponse. The + CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Required. + :type body: 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: An instance of LROPoller that returns CalculateExchangeOperationResultResponse. The + CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_post( + self, body: Union[_models.CalculateExchangeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> LROPoller[_models.CalculateExchangeOperationResultResponse]: + """Calculates the refund amounts and price of the new purchases. + + Calculates price for exchanging ``Reservations`` if there are no policy errors. + + :param body: The request body. Is one of the following types: CalculateExchangeRequest, JSON, + IO[bytes] Required. + :type body: ~azure.mgmt.reservations.models.CalculateExchangeRequest or JSON or IO[bytes] + :return: An instance of LROPoller that returns CalculateExchangeOperationResultResponse. The + CalculateExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CalculateExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CalculateExchangeOperationResultResponse] = 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._post_initial( + body=body, + api_version=api_version, + content_type=content_type, + 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.CalculateExchangeOperationResultResponse, 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.CalculateExchangeOperationResultResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.CalculateExchangeOperationResultResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class ExchangeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.reservations.ReservationsMgmtClient`'s + :attr:`exchange` 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: ReservationsMgmtClientConfiguration = 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") + + def _post_initial(self, body: Union[_models.ExchangeRequest, JSON, IO[bytes]], **kwargs: Any) -> Iterator[bytes]: + 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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_exchange_post_request( + api_version=api_version, + content_type=content_type, + 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 = 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + 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 + + @overload + def begin_post( + self, body: _models.ExchangeRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_post( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Required. + :type body: 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: An instance of LROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_post( + self, body: Union[_models.ExchangeRequest, JSON, IO[bytes]], **kwargs: Any + ) -> LROPoller[_models.ExchangeOperationResultResponse]: + """Exchange Reservation(s). + + Returns one or more ``Reservations`` in exchange for one or more ``Reservation`` purchases. + + :param body: The request body. Is one of the following types: ExchangeRequest, JSON, IO[bytes] + Required. + :type body: ~azure.mgmt.reservations.models.ExchangeRequest or JSON or IO[bytes] + :return: An instance of LROPoller that returns ExchangeOperationResultResponse. The + ExchangeOperationResultResponse is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ExchangeOperationResultResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _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", "2022-11-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ExchangeOperationResultResponse] = 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._post_initial( + body=body, + api_version=api_version, + content_type=content_type, + 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.ExchangeOperationResultResponse, 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.ExchangeOperationResultResponse].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.ExchangeOperationResultResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + +class _ReservationsMgmtClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], ReservationsMgmtClientConfiguration] +): + + @distributed_trace + @api_version_validation( + method_added_on="2022-11-01", + params_added_on={ + "2022-11-01": [ + "api_version", + "subscription_id", + "reserved_resource_type", + "location", + "publisher_id", + "offer_id", + "plan_id", + "filter", + "skip", + "take", + "accept", + ] + }, + api_versions_list=["2022-11-01"], + ) + def get_catalog( + self, + subscription_id: str, + *, + reserved_resource_type: Optional[str] = None, + location: Optional[str] = None, + publisher_id: Optional[str] = None, + offer_id: Optional[str] = None, + plan_id: Optional[str] = None, + filter: Optional[str] = None, + skip: Optional[float] = None, + take: Optional[float] = None, + **kwargs: Any + ) -> ItemPaged["_models.Catalog"]: + """Get the regions and skus that are available for RI purchase for the specified Azure + subscription. + + Get the regions and skus that are available for RI purchase for the specified Azure + subscription. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :keyword reserved_resource_type: The type of the resource for which the skus should be + provided. Default value is None. + :paramtype reserved_resource_type: str + :keyword location: Filters the skus based on the location specified in this parameter. This can + be an azure region or global. Default value is None. + :paramtype location: str + :keyword publisher_id: Publisher id used to get the third party products. Default value is + None. + :paramtype publisher_id: str + :keyword offer_id: Offer id used to get the third party products. Default value is None. + :paramtype offer_id: str + :keyword plan_id: Plan id used to get the third party products. Default value is None. + :paramtype plan_id: str + :keyword filter: May be used to filter by Catalog properties. The filter supports 'eq', 'or', + and 'and'. Default value is None. + :paramtype filter: str + :keyword skip: The number of reservations to skip from the list before returning results. + Default value is None. + :paramtype skip: float + :keyword take: To number of reservations to return. Default value is None. + :paramtype take: float + :return: An iterator like instance of Catalog + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.Catalog] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[List[_models.Catalog]] = 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_mgmt_get_catalog_request( + subscription_id=subscription_id, + reserved_resource_type=reserved_resource_type, + location=location, + publisher_id=publisher_id, + offer_id=offer_id, + plan_id=plan_id, + filter=filter, + skip=skip, + take=take, + api_version=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: + _request = HttpRequest("GET", next_link, headers=_headers) + 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.Catalog], + 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.Error, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + @api_version_validation( + method_added_on="2022-11-01", + params_added_on={"2022-11-01": ["api_version", "subscription_id", "accept"]}, + api_versions_list=["2022-11-01"], + ) + def get_applied_reservation_list(self, subscription_id: str, **kwargs: Any) -> _models.AppliedReservations: + """Get list of applicable ``Reservation``s. + + Get applicable ``Reservation``s that are applied to this subscription or a resource group under + this subscription. + + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. + :type subscription_id: str + :return: AppliedReservations. The AppliedReservations is compatible with MutableMapping + :rtype: ~azure.mgmt.reservations.models.AppliedReservations + :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 = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) + cls: ClsType[_models.AppliedReservations] = kwargs.pop("cls", None) + + _request = build_reservations_mgmt_get_applied_reservation_list_request( + subscription_id=subscription_id, + api_version=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.Error, + 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.AppliedReservations, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_patch.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_patch.py +++ b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/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/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py deleted file mode 100644 index 84e503d8832f..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_operations.py +++ /dev/null @@ -1,905 +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, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import AzureReservationAPIMixinABC, _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, provider_id: str, location: str, resource_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), - "location": _SERIALIZER.url("location", location, "str"), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - } - - _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( - subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - 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", - "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), - "location": _SERIALIZER.url("location", location, "str"), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - } - - _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_update_request( - subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - 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", - "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), - "location": _SERIALIZER.url("location", location, "str"), - "resourceName": _SERIALIZER.url("resource_name", resource_name, "str"), - } - - _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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(subscription_id: str, provider_id: str, location: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), - "location": _SERIALIZER.url("location", location, "str"), - } - - _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 QuotaOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`quota` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get( - self, subscription_id: str, provider_id: str, location: str, resource_name: str, **kwargs: Any - ) -> _models.CurrentQuotaLimitBase: - """Get the current quota (service limit) and usage of a resource. You can use the response from - the GET operation to submit quota update request. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CurrentQuotaLimitBase or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.CurrentQuotaLimitBase] = kwargs.pop("cls", None) - - request = build_get_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - api_version=api_version, - template_url=self.get.metadata["url"], - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - def _create_or_update_initial( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: - 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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] = kwargs.pop( - "cls", None - ) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_quota_request, (IO, bytes)): - _content = create_quota_request - else: - _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") - - request = build_create_or_update_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._create_or_update_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - @overload - def begin_create_or_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: _models.CurrentQuotaLimitBase, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CurrentQuotaLimitBase]: - """Create or update the quota (service limits) of a resource to the requested value. - Steps: - - - #. Make the Get request to get the quota information for specific resource. - #. To increase the quota, update the limit field in the response from Get request to new value. - #. Submit the JSON to the quota request API to update the quota. - The Create quota request may be constructed as follows. The PUT operation can be used to - update the quota. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Quota requests payload. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of - LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_or_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CurrentQuotaLimitBase]: - """Create or update the quota (service limits) of a resource to the requested value. - Steps: - - - #. Make the Get request to get the quota information for specific resource. - #. To increase the quota, update the limit field in the response from Get request to new value. - #. Submit the JSON to the quota request API to update the quota. - The Create quota request may be constructed as follows. The PUT operation can be used to - update the quota. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Quota requests payload. Required. - :type create_quota_request: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of - LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_or_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> LROPoller[_models.CurrentQuotaLimitBase]: - """Create or update the quota (service limits) of a resource to the requested value. - Steps: - - - #. Make the Get request to get the quota information for specific resource. - #. To increase the quota, update the limit field in the response from Get request to new value. - #. Submit the JSON to the quota request API to update the quota. - The Create quota request may be constructed as follows. The PUT operation can be used to - update the quota. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Quota requests payload. Is either a CurrentQuotaLimitBase type or - a IO type. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of - LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CurrentQuotaLimitBase] = 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._create_or_update_initial( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - create_quota_request=create_quota_request, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - def _update_initial( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]: - 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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Union[_models.CurrentQuotaLimitBase, _models.QuotaRequestSubmitResponse201]] = kwargs.pop( - "cls", None - ) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(create_quota_request, (IO, bytes)): - _content = create_quota_request - else: - _json = self._serialize.body(create_quota_request, "CurrentQuotaLimitBase") - - request = build_update_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._update_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("QuotaRequestSubmitResponse201", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - _update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - @overload - def begin_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: _models.CurrentQuotaLimitBase, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CurrentQuotaLimitBase]: - """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. - • To increase the quota, update the limit field from the GET response to a new value. - • To update the quota value, submit the JSON response to the quota request API to update the - quota. - • To update the quota. use the PATCH operation. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Payload for the quota request. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of - LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.CurrentQuotaLimitBase]: - """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. - • To increase the quota, update the limit field from the GET response to a new value. - • To update the quota value, submit the JSON response to the quota request API to update the - quota. - • To update the quota. use the PATCH operation. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Payload for the quota request. Required. - :type create_quota_request: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of - LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update( - self, - subscription_id: str, - provider_id: str, - location: str, - resource_name: str, - create_quota_request: Union[_models.CurrentQuotaLimitBase, IO], - **kwargs: Any - ) -> LROPoller[_models.CurrentQuotaLimitBase]: - """Update the quota (service limits) of this resource to the requested value. - • To get the quota information for specific resource, send a GET request. - • To increase the quota, update the limit field from the GET response to a new value. - • To update the quota value, submit the JSON response to the quota request API to update the - quota. - • To update the quota. use the PATCH operation. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param resource_name: The resource name for a resource provider, such as SKU name for - Microsoft.Compute, Sku or TotalLowPriorityCores for Microsoft.MachineLearningServices. - Required. - :type resource_name: str - :param create_quota_request: Payload for the quota request. Is either a CurrentQuotaLimitBase - type or a IO type. Required. - :type create_quota_request: ~azure.mgmt.reservations.models.CurrentQuotaLimitBase or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either CurrentQuotaLimitBase or An instance of - LROPoller that returns either QuotaRequestSubmitResponse201 or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] or - ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.QuotaRequestSubmitResponse201] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CurrentQuotaLimitBase] = 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._update_initial( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - resource_name=resource_name, - create_quota_request=create_quota_request, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("CurrentQuotaLimitBase", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "original-uri"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}" - } - - @distributed_trace - def list( - self, subscription_id: str, provider_id: str, location: str, **kwargs: Any - ) -> Iterable["_models.CurrentQuotaLimitBase"]: - """Gets a list of current quotas (service limits) and usage for all resources. The response from - the list quota operation can be leveraged to request quota updates. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CurrentQuotaLimitBase or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.CurrentQuotaLimitBase] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.QuotaLimits] = 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( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - 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: - request = HttpRequest("GET", next_link) - 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("QuotaLimits", 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py deleted file mode 100644 index f86a2fcfd396..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_quota_request_status_operations.py +++ /dev/null @@ -1,312 +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 - -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 AzureReservationAPIMixinABC, _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, provider_id: str, location: str, id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), - "location": _SERIALIZER.url("location", location, "str"), - "id": _SERIALIZER.url("id", id, "str"), - } - - _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_request( - subscription_id: str, - provider_id: str, - location: 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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "providerId": _SERIALIZER.url("provider_id", provider_id, "str"), - "location": _SERIALIZER.url("location", location, "str"), - } - - _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") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=1) - 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) - - -class QuotaRequestStatusOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`quota_request_status` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get( - self, subscription_id: str, provider_id: str, location: str, id: str, **kwargs: Any - ) -> _models.QuotaRequestDetails: - """For the specified Azure region (location), get the details and status of the quota request by - the quota request ID for the resources of the resource provider. The PUT request for the quota - (service limit) returns a response with the requestId parameter. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param id: Quota Request ID. Required. - :type id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: QuotaRequestDetails or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.QuotaRequestDetails - :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["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.QuotaRequestDetails] = kwargs.pop("cls", None) - - request = build_get_request( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - id=id, - api_version=api_version, - template_url=self.get.metadata["url"], - 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("QuotaRequestDetails", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests/{id}" - } - - @distributed_trace - def list( - self, - subscription_id: str, - provider_id: str, - location: str, - filter: Optional[str] = None, - top: Optional[int] = None, - skiptoken: Optional[str] = None, - **kwargs: Any - ) -> Iterable["_models.QuotaRequestDetails"]: - """For the specified Azure region (location), subscription, and resource provider, get the history - of the quota requests for the past year. To select specific quota requests, use the oData - filter. - - :param subscription_id: Azure subscription ID. Required. - :type subscription_id: str - :param provider_id: Azure resource provider ID. Required. - :type provider_id: str - :param location: Azure region. Required. - :type location: str - :param filter: .. list-table:: - :header-rows: 1 - - * - Field - - Supported operators - * - requestSubmitTime - - ge, le, eq, gt, lt. Default value is None. - :type filter: str - :param top: Number of records to return. Default value is None. - :type top: int - :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 includes 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 QuotaRequestDetails or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.QuotaRequestDetails] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2020-10-25"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-25")) - cls: ClsType[_models.QuotaRequestDetailsList] = 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( - subscription_id=subscription_id, - provider_id=provider_id, - location=location, - 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: - request = HttpRequest("GET", next_link) - 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("QuotaRequestDetailsList", 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.ExceptionResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimitsRequests" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py deleted file mode 100644 index 542226cd4e04..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_operations.py +++ /dev/null @@ -1,1672 +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, List, Optional, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import AzureReservationAPIMixinABC, _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_available_scopes_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", - "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes", - ) # pylint: disable=line-too-long - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), - } - - _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="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_split_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split") - 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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_merge_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge") - 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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations" - ) - 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["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( - reservation_order_id: str, reservation_id: str, *, expand: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}", - ) # pylint: disable=line-too-long - 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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if expand is not None: - _params["$expand"] = _SERIALIZER.query("expand", expand, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_update_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", - "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), - } - - _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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_archive_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/archive", - ) # 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["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_unarchive_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/unarchive", - ) # pylint: disable=line-too-long - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - "reservationId": _SERIALIZER.url("reservation_id", reservation_id, "str"), - } - - _url: 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="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_revisions_request(reservation_order_id: str, reservation_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions", - ) # pylint: disable=line-too-long - path_format_arguments = { - "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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_all_request( - *, - filter: Optional[str] = None, - orderby: Optional[str] = None, - refresh_summary: Optional[str] = None, - skiptoken: Optional[float] = None, - selected_state: Optional[str] = None, - take: Optional[float] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservations") - - # 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 orderby is not None: - _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") - if refresh_summary is not None: - _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") - if skiptoken is not None: - _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "float") - if selected_state is not None: - _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") - if take is not None: - _params["take"] = _SERIALIZER.query("take", take, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReservationOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`reservation` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - def _available_scopes_initial( - self, - reservation_order_id: str, - reservation_id: str, - body: Union[_models.AvailableScopeRequest, IO], - **kwargs: Any - ) -> _models.AvailableScopeProperties: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AvailableScopeProperties] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "AvailableScopeRequest") - - request = build_available_scopes_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._available_scopes_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("AvailableScopeProperties", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - _available_scopes_initial.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes" - } - - @overload - def begin_available_scopes( - self, - reservation_order_id: str, - reservation_id: str, - body: _models.AvailableScopeRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.AvailableScopeProperties]: - """Get Available Scopes for ``Reservation``. - - Check whether the scopes from request is valid for ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param body: Scopes to be checked for eligibility. Required. - :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either AvailableScopeProperties or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_available_scopes( - self, - reservation_order_id: str, - reservation_id: str, - body: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.AvailableScopeProperties]: - """Get Available Scopes for ``Reservation``. - - Check whether the scopes from request is valid for ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param body: Scopes to be checked for eligibility. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either AvailableScopeProperties or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_available_scopes( - self, - reservation_order_id: str, - reservation_id: str, - body: Union[_models.AvailableScopeRequest, IO], - **kwargs: Any - ) -> LROPoller[_models.AvailableScopeProperties]: - """Get Available Scopes for ``Reservation``. - - Check whether the scopes from request is valid for ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param body: Scopes to be checked for eligibility. Is either a AvailableScopeRequest type or a - IO type. Required. - :type body: ~azure.mgmt.reservations.models.AvailableScopeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either AvailableScopeProperties or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.AvailableScopeProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AvailableScopeProperties] = 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._available_scopes_initial( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("AvailableScopeProperties", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_available_scopes.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/availableScopes" - } - - def _split_initial( - self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any - ) -> Optional[List[_models.ReservationResponse]]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[List[_models.ReservationResponse]]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "SplitRequest") - - request = build_split_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._split_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _split_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} - - @overload - def begin_split( - self, - reservation_order_id: str, - body: _models.SplitRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[List[_models.ReservationResponse]]: - """Split the ``Reservation``. - - Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to Split a reservation item. Required. - :type body: ~azure.mgmt.reservations.models.SplitRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either list of ReservationResponse or the result - of cls(response) - :rtype: - ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_split( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[List[_models.ReservationResponse]]: - """Split the ``Reservation``. - - Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to Split a reservation item. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either list of ReservationResponse or the result - of cls(response) - :rtype: - ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_split( - self, reservation_order_id: str, body: Union[_models.SplitRequest, IO], **kwargs: Any - ) -> LROPoller[List[_models.ReservationResponse]]: - """Split the ``Reservation``. - - Split a ``Reservation`` into two ``Reservation``\ s with specified quantity distribution. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to Split a reservation item. Is either a SplitRequest type or a - IO type. Required. - :type body: ~azure.mgmt.reservations.models.SplitRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either list of ReservationResponse or the result - of cls(response) - :rtype: - ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[List[_models.ReservationResponse]] = 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._split_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_split.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split"} - - def _merge_initial( - self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any - ) -> Optional[List[_models.ReservationResponse]]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[List[_models.ReservationResponse]]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "MergeRequest") - - request = build_merge_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._merge_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _merge_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} - - @overload - def begin_merge( - self, - reservation_order_id: str, - body: _models.MergeRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[List[_models.ReservationResponse]]: - """Merges two ``Reservation``\ s. - - Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s - being merged must have same properties. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. Required. - :type body: ~azure.mgmt.reservations.models.MergeRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either list of ReservationResponse or the result - of cls(response) - :rtype: - ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_merge( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[List[_models.ReservationResponse]]: - """Merges two ``Reservation``\ s. - - Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s - being merged must have same properties. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either list of ReservationResponse or the result - of cls(response) - :rtype: - ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_merge( - self, reservation_order_id: str, body: Union[_models.MergeRequest, IO], **kwargs: Any - ) -> LROPoller[List[_models.ReservationResponse]]: - """Merges two ``Reservation``\ s. - - Merge the specified ``Reservation``\ s into a new ``Reservation``. The two ``Reservation``\ s - being merged must have same properties. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for commercial request for a reservation. Is either a - MergeRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.MergeRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either list of ReservationResponse or the result - of cls(response) - :rtype: - ~azure.core.polling.LROPoller[list[~azure.mgmt.reservations.models.ReservationResponse]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[List[_models.ReservationResponse]] = 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._merge_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("[ReservationResponse]", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_merge.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge"} - - @distributed_trace - def list(self, reservation_order_id: str, **kwargs: Any) -> Iterable["_models.ReservationResponse"]: - """Get ``Reservation``\ s in a given reservation Order. - - List ``Reservation``\ s within a single ``ReservationOrder``. - - :param reservation_order_id: Order Id of the reservation. Required. - :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 ReservationResponse or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationList] = 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( - 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: - request = HttpRequest("GET", next_link) - 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("ReservationList", 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.Error, 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.Capacity/reservationOrders/{reservationOrderId}/reservations"} - - @distributed_trace - def get( - self, reservation_order_id: str, reservation_id: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.ReservationResponse: - """Get ``Reservation`` details. - - Get specific ``Reservation`` details. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param expand: Supported value of this query is renewProperties. Default value is None. - :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ReservationResponse - :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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationResponse] = kwargs.pop("cls", None) - - request = build_get_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - expand=expand, - api_version=api_version, - template_url=self.get.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ReservationResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" - } - - def _update_initial( - self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any - ) -> Optional[_models.ReservationResponse]: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ReservationResponse]] = 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, "Patch") - - request = build_update_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._update_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = None - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ReservationResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized - - _update_initial.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" - } - - @overload - def begin_update( - self, - reservation_order_id: str, - reservation_id: str, - parameters: _models.Patch, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ReservationResponse]: - """Updates a ``Reservation``. - - Updates the applied scopes of the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param parameters: Information needed to patch a reservation item. Required. - :type parameters: ~azure.mgmt.reservations.models.Patch - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationResponse or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update( - self, - reservation_order_id: str, - reservation_id: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ReservationResponse]: - """Updates a ``Reservation``. - - Updates the applied scopes of the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param parameters: Information needed to patch a reservation item. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationResponse or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update( - self, reservation_order_id: str, reservation_id: str, parameters: Union[_models.Patch, IO], **kwargs: Any - ) -> LROPoller[_models.ReservationResponse]: - """Updates a ``Reservation``. - - Updates the applied scopes of the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :param parameters: Information needed to patch a reservation item. Is either a Patch type or a - IO type. Required. - :type parameters: ~azure.mgmt.reservations.models.Patch or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationResponse or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationResponse] = 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._update_initial( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ReservationResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_update.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}" - } - - @distributed_trace - def archive( # pylint: disable=inconsistent-return-statements - self, reservation_order_id: str, reservation_id: str, **kwargs: Any - ) -> None: - """Archive a ``Reservation``. - - Archiving a ``Reservation`` moves it to ``Archived`` state. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_archive_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - template_url=self.archive.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - archive.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/archive" - } - - @distributed_trace - def unarchive( # pylint: disable=inconsistent-return-statements - self, reservation_order_id: str, reservation_id: str, **kwargs: Any - ) -> None: - """Unarchive a ``Reservation``. - - Restores a ``Reservation`` to the state it was before archiving. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[None] = kwargs.pop("cls", None) - - request = build_unarchive_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - template_url=self.unarchive.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - unarchive.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/unarchive" - } - - @distributed_trace - def list_revisions( - self, reservation_order_id: str, reservation_id: str, **kwargs: Any - ) -> Iterable["_models.ReservationResponse"]: - """Get ``Reservation`` revisions. - - List of all the revisions for the ``Reservation``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param reservation_id: Id of the reservation item. Required. - :type reservation_id: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationResponse or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationList] = 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_revisions_request( - reservation_order_id=reservation_order_id, - reservation_id=reservation_id, - api_version=api_version, - template_url=self.list_revisions.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - 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("ReservationList", 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list_revisions.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions" - } - - @distributed_trace - def list_all( - self, - filter: Optional[str] = None, - orderby: Optional[str] = None, - refresh_summary: Optional[str] = None, - skiptoken: Optional[float] = None, - selected_state: Optional[str] = None, - take: Optional[float] = None, - **kwargs: Any - ) -> Iterable["_models.ReservationResponse"]: - """List the reservations and the roll up counts of reservations group by provisioning states that - the user has access to in the current tenant. - - :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', - and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Reservation - properties include sku/name, properties/{appliedScopeType, archived, displayName, - displayProvisioningState, effectiveDateTime, expiryDate, expiryDateTime, provisioningState, - quantity, renew, reservedResourceType, term, userFriendlyAppliedScopeType, - userFriendlyRenewState}. Default value is None. - :type filter: str - :param orderby: May be used to sort order by reservation properties. Default value is None. - :type orderby: str - :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations - group by provisioning states. Default value is None. - :type refresh_summary: str - :param skiptoken: The number of reservations to skip from the list before returning results. - Default value is None. - :type skiptoken: float - :param selected_state: The selected provisioning state. Default value is None. - :type selected_state: str - :param take: To number of reservations to return. Default value is None. - :type take: float - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationResponse or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationsListResult] = 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_all_request( - filter=filter, - orderby=orderby, - refresh_summary=refresh_summary, - skiptoken=skiptoken, - selected_state=selected_state, - take=take, - api_version=api_version, - template_url=self.list_all.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - 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("ReservationsListResult", 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_all.metadata = {"url": "/providers/Microsoft.Capacity/reservations"} diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py deleted file mode 100644 index f6a553da660c..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_reservation_order_operations.py +++ /dev/null @@ -1,763 +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, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import AzureReservationAPIMixinABC, _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_calculate_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/calculatePrice") - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders") - - # 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_purchase_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}") - 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["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_get_request(reservation_order_id: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}") - path_format_arguments = { - "reservationOrderId": _SERIALIZER.url("reservation_order_id", reservation_order_id, "str"), - } - - _url: str = _format_url_section(_url, **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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_change_directory_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory" - ) - 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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReservationOrderOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`reservation_order` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def calculate( - self, body: _models.PurchaseRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CalculatePriceResponse: - """Calculate price for a ``ReservationOrder``. - - Calculate price for placing a ``ReservationOrder``. - - :param body: Information needed for calculate or purchase reservation. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculatePriceResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def calculate( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CalculatePriceResponse: - """Calculate price for a ``ReservationOrder``. - - Calculate price for placing a ``ReservationOrder``. - - :param body: Information needed for calculate or purchase reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculatePriceResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def calculate(self, body: Union[_models.PurchaseRequest, IO], **kwargs: Any) -> _models.CalculatePriceResponse: - """Calculate price for a ``ReservationOrder``. - - Calculate price for placing a ``ReservationOrder``. - - :param body: Information needed for calculate or purchase reservation. Is either a - PurchaseRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CalculatePriceResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.CalculatePriceResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.CalculatePriceResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "PurchaseRequest") - - request = build_calculate_request( - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.calculate.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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("CalculatePriceResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - calculate.metadata = {"url": "/providers/Microsoft.Capacity/calculatePrice"} - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.ReservationOrderResponse"]: - """Get all ``ReservationOrder``\ s. - - List of all the ``ReservationOrder``\ s that the user has access to in the current tenant. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationOrderResponse or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationOrderList] = 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( - 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: - request = HttpRequest("GET", next_link) - 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("ReservationOrderList", 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.Error, 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.Capacity/reservationOrders"} - - def _purchase_initial( - self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any - ) -> _models.ReservationOrderResponse: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationOrderResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "PurchaseRequest") - - request = build_purchase_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._purchase_initial.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - _purchase_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} - - @overload - def begin_purchase( - self, - reservation_order_id: str, - body: _models.PurchaseRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ReservationOrderResponse]: - """Purchase ``ReservationOrder``. - - Purchase ``ReservationOrder`` and create resource under the specified URI. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationOrderResponse or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_purchase( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.ReservationOrderResponse]: - """Purchase ``ReservationOrder``. - - Purchase ``ReservationOrder`` and create resource under the specified URI. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationOrderResponse or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_purchase( - self, reservation_order_id: str, body: Union[_models.PurchaseRequest, IO], **kwargs: Any - ) -> LROPoller[_models.ReservationOrderResponse]: - """Purchase ``ReservationOrder``. - - Purchase ``ReservationOrder`` and create resource under the specified URI. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for calculate or purchase reservation. Is either a - PurchaseRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.PurchaseRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationOrderResponse or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationOrderResponse] = 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._purchase_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_purchase.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} - - @distributed_trace - def get( - self, reservation_order_id: str, expand: Optional[str] = None, **kwargs: Any - ) -> _models.ReservationOrderResponse: - """Get a specific ``ReservationOrder``. - - Get the details of the ``ReservationOrder``. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param expand: May be used to expand the planInformation. Default value is None. - :type expand: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ReservationOrderResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ReservationOrderResponse - :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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - cls: ClsType[_models.ReservationOrderResponse] = kwargs.pop("cls", None) - - request = build_get_request( - reservation_order_id=reservation_order_id, - expand=expand, - api_version=api_version, - template_url=self.get.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}"} - - @overload - def change_directory( - self, - reservation_order_id: str, - body: _models.ChangeDirectoryRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ChangeDirectoryResponse: - """Change directory of ``ReservationOrder``. - - Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified - tenant id. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. Required. - :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChangeDirectoryResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def change_directory( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ChangeDirectoryResponse: - """Change directory of ``ReservationOrder``. - - Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified - tenant id. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChangeDirectoryResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def change_directory( - self, reservation_order_id: str, body: Union[_models.ChangeDirectoryRequest, IO], **kwargs: Any - ) -> _models.ChangeDirectoryResponse: - """Change directory of ``ReservationOrder``. - - Change directory (tenant) of ``ReservationOrder`` and all ``Reservation`` under it to specified - tenant id. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed to change directory of reservation order. Is either a - ChangeDirectoryRequest type or a IO type. Required. - :type body: ~azure.mgmt.reservations.models.ChangeDirectoryRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ChangeDirectoryResponse or the result of cls(response) - :rtype: ~azure.mgmt.reservations.models.ChangeDirectoryResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ChangeDirectoryResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "ChangeDirectoryRequest") - - request = build_change_directory_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.change_directory.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - 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.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("ChangeDirectoryResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - change_directory.metadata = { - "url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/changeDirectory" - } diff --git a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py b/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py deleted file mode 100644 index 334b44df79a8..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/azure/mgmt/reservations/operations/_return_operations_operations.py +++ /dev/null @@ -1,296 +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, Optional, TypeVar, Union, cast, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import AzureReservationAPIMixinABC, _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_post_request(reservation_order_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-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", "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return") - 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["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class ReturnOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.reservations.AzureReservationAPI`'s - :attr:`return_operations` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - def _post_initial( - self, reservation_order_id: str, body: Union[_models.RefundRequest, IO], **kwargs: Any - ) -> Union[_models.ReservationOrderResponse, _models.RefundResponse]: - 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["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Union[_models.ReservationOrderResponse, _models.RefundResponse]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(body, (IO, bytes)): - _content = body - else: - _json = self._serialize.body(body, "RefundRequest") - - request = build_post_request( - reservation_order_id=reservation_order_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self._post_initial.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, 202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = self._deserialize("RefundResponse", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - _post_initial.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return"} - - @overload - def begin_post( - self, - reservation_order_id: str, - body: _models.RefundRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.ReservationOrderResponse]: - """Return a reservation. - - Return a reservation and get refund information. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for returning reservation. Required. - :type body: ~azure.mgmt.reservations.models.RefundRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationOrderResponse or An instance - of LROPoller that returns either RefundResponse or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - or ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.RefundResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_post( - self, reservation_order_id: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.ReservationOrderResponse]: - """Return a reservation. - - Return a reservation and get refund information. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for returning reservation. Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationOrderResponse or An instance - of LROPoller that returns either RefundResponse or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - or ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.RefundResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_post( - self, reservation_order_id: str, body: Union[_models.RefundRequest, IO], **kwargs: Any - ) -> LROPoller[_models.ReservationOrderResponse]: - """Return a reservation. - - Return a reservation and get refund information. - - :param reservation_order_id: Order Id of the reservation. Required. - :type reservation_order_id: str - :param body: Information needed for returning reservation. Is either a RefundRequest type or a - IO type. Required. - :type body: ~azure.mgmt.reservations.models.RefundRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - :return: An instance of LROPoller that returns either ReservationOrderResponse or An instance - of LROPoller that returns either RefundResponse or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.ReservationOrderResponse] - or ~azure.core.polling.LROPoller[~azure.mgmt.reservations.models.RefundResponse] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: Literal["2022-11-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-11-01")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ReservationOrderResponse] = 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._post_initial( - reservation_order_id=reservation_order_id, - body=body, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("ReservationOrderResponse", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post.metadata = {"url": "/providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/return"} diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/archive.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/archive.py index 72b6876ec37f..216966d0347c 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/archive.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/archive.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,17 +25,16 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) - response = client.reservation.archive( + client.reservation.archive( reservation_order_id="276e7ae4-84d0-4da6-ab4b-d6b94f3557da", reservation_id="356e7ae4-84d0-4da6-ab4b-d6b94f3557da", ) - print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/Archive.json +# x-ms-original-file: 2022-11-01/Archive.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_exchange.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_exchange.py index f9e48e7b3d35..7a3c5d5d6560 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_exchange.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_exchange.py @@ -1,13 +1,15 @@ +# 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +26,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -76,6 +78,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/CalculateExchange.json +# x-ms-original-file: 2022-11-01/CalculateExchange.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_refund.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_refund.py index 93aa685f4f8d..04a086c2a8cb 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_refund.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_refund.py @@ -1,13 +1,15 @@ +# 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +26,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -44,6 +46,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/CalculateRefund.json +# x-ms-original-file: 2022-11-01/CalculateRefund.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_reservation_order.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_reservation_order.py index ab798f14b78b..0218c1235817 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_reservation_order.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/calculate_reservation_order.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -48,6 +49,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/CalculateReservationOrder.json +# x-ms-original-file: 2022-11-01/CalculateReservationOrder.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/change_directory_reservation_order.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/change_directory_reservation_order.py index ea186f527d7f..41a7d1d15c87 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/change_directory_reservation_order.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/change_directory_reservation_order.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/ChangeDirectoryReservationOrder.json +# x-ms-original-file: 2022-11-01/ChangeDirectoryReservationOrder.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/exchange.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/exchange.py index 06330f0efa39..498d6a6580b4 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/exchange.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/exchange.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/Exchange.json +# x-ms-original-file: 2022-11-01/Exchange.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_applied_reservations.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_applied_reservations.py index 47a4ed365fcc..841a10209049 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_applied_reservations.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_applied_reservations.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetAppliedReservations.json +# x-ms-original-file: 2022-11-01/GetAppliedReservations.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_available_scope.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_available_scope.py index 3e04d4091f7d..7d6f2fa6766d 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_available_scope.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_available_scope.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetAvailableScope.json +# x-ms-original-file: 2022-11-01/GetAvailableScope.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_catalog.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_catalog.py index 175fb8882356..91d0d682b474 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_catalog.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_catalog.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetCatalog.json +# x-ms-original-file: 2022-11-01/GetCatalog.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_one_sku_usages.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_one_sku_usages.py index 4d9097993f14..6d13699d6266 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_one_sku_usages.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_one_sku_usages.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/getComputeOneSkuUsages.json +# x-ms-original-file: 2020-10-25/getComputeOneSkuUsages.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_usages.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_usages.py index a8c4a5d0d81d..2c2372e1295e 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_usages.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_compute_usages.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/getComputeUsages.json +# x-ms-original-file: 2020-10-25/getComputeUsages.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_machine_learning_services_usages.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_machine_learning_services_usages.py index f4a8f4fd673b..d4ed812d3afd 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_machine_learning_services_usages.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_machine_learning_services_usages.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/getMachineLearningServicesUsages.json +# x-ms-original-file: 2020-10-25/getMachineLearningServicesUsages.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_operations.py index 231e0b8f9c65..4c48411b4d4d 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_operations.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_operations.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -33,6 +34,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetOperations.json +# x-ms-original-file: 2022-11-01/GetOperations.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_by_id.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_by_id.py index be58f5afbfb1..1519ed97e833 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_by_id.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_by_id.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/getQuotaRequestStatusById.json +# x-ms-original-file: 2020-10-25/getQuotaRequestStatusById.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_failed.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_failed.py index 61e7e7340905..89c763043182 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_failed.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_failed.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -37,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/getQuotaRequestStatusFailed.json +# x-ms-original-file: 2020-10-25/getQuotaRequestStatusFailed.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_in_progress.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_in_progress.py index 8ac441fdb796..f7e56a588974 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_in_progress.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_request_status_in_progress.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,19 +25,19 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) response = client.quota_request_status.get( subscription_id="00000000-0000-0000-0000-000000000000", provider_id="Microsoft.Compute", - location="eastus", + location="westus", id="2B5C8515-37D8-4B6A-879B-CD641A2CF605", ) print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/getQuotaRequestStatusInProgress.json +# x-ms-original-file: 2020-10-25/getQuotaRequestStatusInProgress.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_requests_history.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_requests_history.py index 67ae3cc42275..fb1db9070d13 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_requests_history.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_quota_requests_history.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -37,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/getQuotaRequestsHistory.json +# x-ms-original-file: 2020-10-25/getQuotaRequestsHistory.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_details.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_details.py index 8f9343cbad94..b8e521227e4a 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_details.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_details.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -35,6 +36,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetReservationDetails.json +# x-ms-original-file: 2022-11-01/GetReservationDetails.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details.py index 26cf37d6d3c3..15c4525505d4 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetReservationOrderDetails.json +# x-ms-original-file: 2022-11-01/GetReservationOrderDetails.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details_with_expand_plan_information.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details_with_expand_plan_information.py index 8890ff2de990..c72f08392f01 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details_with_expand_plan_information.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_order_details_with_expand_plan_information.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -34,6 +35,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetReservationOrderDetailsWithExpandPlanInformation.json +# x-ms-original-file: 2022-11-01/GetReservationOrderDetailsWithExpandPlanInformation.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_orders.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_orders.py index e77ec60f450a..e14b2de66b72 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_orders.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_orders.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -33,6 +34,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetReservationOrders.json +# x-ms-original-file: 2022-11-01/GetReservationOrders.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_revisions.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_revisions.py index 93de7e0bac0b..8b1447254004 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_revisions.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservation_revisions.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -36,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetReservationRevisions.json +# x-ms-original-file: 2022-11-01/GetReservationRevisions.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations.py index 5f98fcaa6efb..92a83369cd63 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -33,6 +34,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetReservations.json +# x-ms-original-file: 2022-11-01/GetReservations.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations_from_order.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations_from_order.py index 59c758aac557..cdb0a614704c 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations_from_order.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/get_reservations_from_order.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -35,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/GetReservationsFromOrder.json +# x-ms-original-file: 2022-11-01/GetReservationsFromOrder.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/merge_reservations.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/merge_reservations.py index 9c21137aa048..21cadb6eacb2 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/merge_reservations.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/merge_reservations.py @@ -1,13 +1,15 @@ +# 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +26,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -42,6 +44,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/MergeReservations.json +# x-ms-original-file: 2022-11-01/MergeReservations.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/patch_compute_quota_request.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/patch_compute_quota_request.py index 22d01d629f32..a20d319e07e6 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/patch_compute_quota_request.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/patch_compute_quota_request.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -38,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/patchComputeQuotaRequest.json +# x-ms-original-file: 2020-10-25/patchComputeQuotaRequest.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/purchase_reservation_order.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/purchase_reservation_order.py index b3b2ad0b0e62..0a211610facd 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/purchase_reservation_order.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/purchase_reservation_order.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -50,6 +51,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/PurchaseReservationOrder.json +# x-ms-original-file: 2022-11-01/PurchaseReservationOrder.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/put_compute_one_sku_quota_request.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/put_compute_one_sku_quota_request.py index 37bc46d53cab..ef279b62bb17 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/put_compute_one_sku_quota_request.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/put_compute_one_sku_quota_request.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -38,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/putComputeOneSkuQuotaRequest.json +# x-ms-original-file: 2020-10-25/putComputeOneSkuQuotaRequest.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_dedicated.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_dedicated.py index 9df20745406c..1e71c8941011 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_dedicated.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_dedicated.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -45,6 +46,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/putMachineLearningServicesQuotaRequestDedicated.json +# x-ms-original-file: 2020-10-25/putMachineLearningServicesQuotaRequestDedicated.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_low_priority.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_low_priority.py index 537bcf84ff23..14f66d72166d 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_low_priority.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/put_machine_learning_services_quota_request_low_priority.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -45,6 +46,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2020-10-25/examples/putMachineLearningServicesQuotaRequestLowPriority.json +# x-ms-original-file: 2020-10-25/putMachineLearningServicesQuotaRequestLowPriority.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/return.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/return.py index 8fae4a796a44..41a65295f2ab 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/return.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/return.py @@ -1,13 +1,15 @@ +# 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +26,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -45,6 +47,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/Return.json +# x-ms-original-file: 2022-11-01/Return.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/split_reservation.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/split_reservation.py index f27cf34b6423..e4bdbaabd30a 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/split_reservation.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/split_reservation.py @@ -1,13 +1,15 @@ +# 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +26,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -40,6 +42,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/SplitReservation.json +# x-ms-original-file: 2022-11-01/SplitReservation.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/unarchive.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/unarchive.py index 87e76952bf14..4ee152c0c503 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/unarchive.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/unarchive.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,17 +25,16 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) - response = client.reservation.unarchive( + client.reservation.unarchive( reservation_order_id="276e7ae4-84d0-4da6-ab4b-d6b94f3557da", reservation_id="356e7ae4-84d0-4da6-ab4b-d6b94f3557da", ) - print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/Unarchive.json +# x-ms-original-file: 2022-11-01/Unarchive.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_samples/update_reservation.py b/sdk/reservations/azure-mgmt-reservations/generated_samples/update_reservation.py index 3f694f7548b0..963c23c9b5b0 100644 --- a/sdk/reservations/azure-mgmt-reservations/generated_samples/update_reservation.py +++ b/sdk/reservations/azure-mgmt-reservations/generated_samples/update_reservation.py @@ -2,12 +2,13 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft 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.reservations import AzureReservationAPI + +from azure.mgmt.reservations import ReservationsMgmtClient """ # PREREQUISITES @@ -24,7 +25,7 @@ def main(): - client = AzureReservationAPI( + client = ReservationsMgmtClient( credential=DefaultAzureCredential(), ) @@ -36,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/reservations/resource-manager/Microsoft.Capacity/stable/2022-11-01/examples/UpdateReservation.json +# x-ms-original-file: 2022-11-01/UpdateReservation.json if __name__ == "__main__": main() diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/conftest.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/conftest.py new file mode 100644 index 000000000000..b45b2b443e6e --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/conftest.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 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): + reservationsmgmt_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + reservationsmgmt_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + reservationsmgmt_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + reservationsmgmt_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=reservationsmgmt_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=reservationsmgmt_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=reservationsmgmt_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=reservationsmgmt_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/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt.py new file mode 100644 index 000000000000..86d6cb7e3963 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt.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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmt(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get_catalog(self, resource_group): + response = self.client.get_catalog( + subscription_id="str", + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_get_applied_reservation_list(self, resource_group): + response = self.client.get_applied_reservation_list( + subscription_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_async.py new file mode 100644 index 000000000000..0265337bec63 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_async.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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_get_catalog(self, resource_group): + response = self.client.get_catalog( + subscription_id="str", + api_version="2022-11-01", + ) + 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_get_applied_reservation_list(self, resource_group): + response = await self.client.get_applied_reservation_list( + subscription_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations.py new file mode 100644 index 000000000000..57a49d66f20b --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtCalculateExchangeOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_calculate_exchange_begin_post(self, resource_group): + response = self.client.calculate_exchange.begin_post( + body={ + "properties": { + "reservationsToExchange": [{"quantity": 0, "reservationId": "str"}], + "reservationsToPurchase": [ + { + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + } + ], + "savingsPlansToPurchase": [ + { + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "billingPlan": "str", + "billingScopeId": "str", + "commitment": {"amount": 0.0, "currencyCode": "str", "grain": "str"}, + "displayName": "str", + "term": "str", + }, + "sku": {"name": "str"}, + } + ], + } + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations_async.py new file mode 100644 index 000000000000..4cb8216eb174 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_exchange_operations_async.py @@ -0,0 +1,83 @@ +# 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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtCalculateExchangeOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_calculate_exchange_begin_post(self, resource_group): + response = await ( + await self.client.calculate_exchange.begin_post( + body={ + "properties": { + "reservationsToExchange": [{"quantity": 0, "reservationId": "str"}], + "reservationsToPurchase": [ + { + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + } + ], + "savingsPlansToPurchase": [ + { + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "billingPlan": "str", + "billingScopeId": "str", + "commitment": {"amount": 0.0, "currencyCode": "str", "grain": "str"}, + "displayName": "str", + "term": "str", + }, + "sku": {"name": "str"}, + } + ], + } + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_operations.py new file mode 100644 index 000000000000..22f2d3ad511e --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtCalculateRefundOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_calculate_refund_post(self, resource_group): + response = self.client.calculate_refund.post( + reservation_order_id="str", + body={ + "id": "str", + "properties": {"reservationToReturn": {"quantity": 0, "reservationId": "str"}, "scope": "str"}, + }, + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_operations_async.py new file mode 100644 index 000000000000..fe7caaf6611e --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_calculate_refund_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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtCalculateRefundOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_calculate_refund_post(self, resource_group): + response = await self.client.calculate_refund.post( + reservation_order_id="str", + body={ + "id": "str", + "properties": {"reservationToReturn": {"quantity": 0, "reservationId": "str"}, "scope": "str"}, + }, + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_operations.py new file mode 100644 index 000000000000..a7da1047b712 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtExchangeOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_exchange_begin_post(self, resource_group): + response = self.client.exchange.begin_post( + body={"properties": {"sessionId": "str"}}, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_operations_async.py new file mode 100644 index 000000000000..e5b6b35e6793 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_exchange_operations_async.py @@ -0,0 +1,33 @@ +# 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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtExchangeOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_exchange_begin_post(self, resource_group): + response = await ( + await self.client.exchange.begin_post( + body={"properties": {"sessionId": "str"}}, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_operations.py new file mode 100644 index 000000000000..32f4d88a578b --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtOperationOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operation_list(self, resource_group): + response = self.client.operation.list( + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_operations_async.py new file mode 100644 index 000000000000..178a11410a1b --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_operation_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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtOperationOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operation_list(self, resource_group): + response = self.client.operation.list( + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations.py new file mode 100644 index 000000000000..4a6367aebf98 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations.py @@ -0,0 +1,118 @@ +# 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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtQuotaOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_quota_get(self, resource_group): + response = self.client.quota.get( + subscription_id="str", + provider_id="str", + location="str", + resource_name="str", + api_version="2020-10-25", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_quota_begin_create_or_update(self, resource_group): + response = self.client.quota.begin_create_or_update( + subscription_id="str", + provider_id="str", + location="str", + resource_name="str", + create_quota_request={ + "id": "str", + "name": "str", + "properties": { + "currentValue": 0, + "limit": 0, + "name": {"localizedValue": "str", "value": "str"}, + "properties": {}, + "quotaPeriod": "str", + "resourceType": "str", + "unit": "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", + }, + api_version="2020-10-25", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_quota_begin_update(self, resource_group): + response = self.client.quota.begin_update( + subscription_id="str", + provider_id="str", + location="str", + resource_name="str", + create_quota_request={ + "id": "str", + "name": "str", + "properties": { + "currentValue": 0, + "limit": 0, + "name": {"localizedValue": "str", "value": "str"}, + "properties": {}, + "quotaPeriod": "str", + "resourceType": "str", + "unit": "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", + }, + api_version="2020-10-25", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_quota_list(self, resource_group): + response = self.client.quota.list( + subscription_id="str", + provider_id="str", + location="str", + api_version="2020-10-25", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations_async.py new file mode 100644 index 000000000000..f4834e5f12a6 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_operations_async.py @@ -0,0 +1,123 @@ +# 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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtQuotaOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_quota_get(self, resource_group): + response = await self.client.quota.get( + subscription_id="str", + provider_id="str", + location="str", + resource_name="str", + api_version="2020-10-25", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_quota_begin_create_or_update(self, resource_group): + response = await ( + await self.client.quota.begin_create_or_update( + subscription_id="str", + provider_id="str", + location="str", + resource_name="str", + create_quota_request={ + "id": "str", + "name": "str", + "properties": { + "currentValue": 0, + "limit": 0, + "name": {"localizedValue": "str", "value": "str"}, + "properties": {}, + "quotaPeriod": "str", + "resourceType": "str", + "unit": "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", + }, + api_version="2020-10-25", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_quota_begin_update(self, resource_group): + response = await ( + await self.client.quota.begin_update( + subscription_id="str", + provider_id="str", + location="str", + resource_name="str", + create_quota_request={ + "id": "str", + "name": "str", + "properties": { + "currentValue": 0, + "limit": 0, + "name": {"localizedValue": "str", "value": "str"}, + "properties": {}, + "quotaPeriod": "str", + "resourceType": "str", + "unit": "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", + }, + api_version="2020-10-25", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_quota_list(self, resource_group): + response = self.client.quota.list( + subscription_id="str", + provider_id="str", + location="str", + api_version="2020-10-25", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations.py new file mode 100644 index 000000000000..11a19ad1b97a --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations.py @@ -0,0 +1,46 @@ +# 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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtQuotaRequestStatusOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_quota_request_status_get(self, resource_group): + response = self.client.quota_request_status.get( + subscription_id="str", + provider_id="str", + location="str", + id="str", + api_version="2020-10-25", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_quota_request_status_list(self, resource_group): + response = self.client.quota_request_status.list( + subscription_id="str", + provider_id="str", + location="str", + api_version="2020-10-25", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations_async.py new file mode 100644 index 000000000000..bea61e4520c4 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_quota_request_status_operations_async.py @@ -0,0 +1,47 @@ +# 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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtQuotaRequestStatusOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_quota_request_status_get(self, resource_group): + response = await self.client.quota_request_status.get( + subscription_id="str", + provider_id="str", + location="str", + id="str", + api_version="2020-10-25", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_quota_request_status_list(self, resource_group): + response = self.client.quota_request_status.list( + subscription_id="str", + provider_id="str", + location="str", + api_version="2020-10-25", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations.py new file mode 100644 index 000000000000..27148dc89626 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations.py @@ -0,0 +1,180 @@ +# 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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtReservationOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_get(self, resource_group): + response = self.client.reservation.get( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_begin_update(self, resource_group): + response = self.client.reservation.begin_update( + reservation_order_id="str", + reservation_id="str", + parameters={ + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "instanceFlexibility": "str", + "name": "str", + "renew": bool, + "renewProperties": { + "purchaseProperties": { + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + } + }, + "reviewDateTime": "2020-02-20 00:00:00", + } + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_list(self, resource_group): + response = self.client.reservation.list( + reservation_order_id="str", + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_begin_available_scopes(self, resource_group): + response = self.client.reservation.begin_available_scopes( + reservation_order_id="str", + reservation_id="str", + body={"properties": {"scopes": ["str"]}}, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_archive(self, resource_group): + response = self.client.reservation.archive( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_unarchive(self, resource_group): + response = self.client.reservation.unarchive( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_list_revisions(self, resource_group): + response = self.client.reservation.list_revisions( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_begin_split(self, resource_group): + response = self.client.reservation.begin_split( + reservation_order_id="str", + body={"properties": {"quantities": [0], "reservationId": "str"}}, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_begin_merge(self, resource_group): + response = self.client.reservation.begin_merge( + reservation_order_id="str", + body={"properties": {"sources": ["str"]}}, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_list_all(self, resource_group): + response = self.client.reservation.list_all( + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations_async.py new file mode 100644 index 000000000000..0be9e88aa830 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_operations_async.py @@ -0,0 +1,189 @@ +# 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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtReservationOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_get(self, resource_group): + response = await self.client.reservation.get( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_begin_update(self, resource_group): + response = await ( + await self.client.reservation.begin_update( + reservation_order_id="str", + reservation_id="str", + parameters={ + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "instanceFlexibility": "str", + "name": "str", + "renew": bool, + "renewProperties": { + "purchaseProperties": { + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + } + }, + "reviewDateTime": "2020-02-20 00:00:00", + } + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_list(self, resource_group): + response = self.client.reservation.list( + reservation_order_id="str", + api_version="2022-11-01", + ) + 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_begin_available_scopes(self, resource_group): + response = await ( + await self.client.reservation.begin_available_scopes( + reservation_order_id="str", + reservation_id="str", + body={"properties": {"scopes": ["str"]}}, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_archive(self, resource_group): + response = await self.client.reservation.archive( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_unarchive(self, resource_group): + response = await self.client.reservation.unarchive( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_list_revisions(self, resource_group): + response = self.client.reservation.list_revisions( + reservation_order_id="str", + reservation_id="str", + api_version="2022-11-01", + ) + 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_begin_split(self, resource_group): + response = await ( + await self.client.reservation.begin_split( + reservation_order_id="str", + body={"properties": {"quantities": [0], "reservationId": "str"}}, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_begin_merge(self, resource_group): + response = await ( + await self.client.reservation.begin_merge( + reservation_order_id="str", + body={"properties": {"sources": ["str"]}}, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_list_all(self, resource_group): + response = self.client.reservation.list_all( + api_version="2022-11-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations.py new file mode 100644 index 000000000000..0aa65d45484d --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations.py @@ -0,0 +1,121 @@ +# 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.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtReservationOrderOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_order_get(self, resource_group): + response = self.client.reservation_order.get( + reservation_order_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_order_begin_purchase(self, resource_group): + response = self.client.reservation_order.begin_purchase( + reservation_order_id="str", + body={ + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_order_list(self, resource_group): + response = self.client.reservation_order.list( + api_version="2022-11-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_order_change_directory(self, resource_group): + response = self.client.reservation_order.change_directory( + reservation_order_id="str", + body={"destinationTenantId": "str"}, + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_reservation_order_calculate(self, resource_group): + response = self.client.reservation_order.calculate( + body={ + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + }, + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations_async.py new file mode 100644 index 000000000000..c0b33026a577 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_reservation_order_operations_async.py @@ -0,0 +1,124 @@ +# 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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtReservationOrderOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_order_get(self, resource_group): + response = await self.client.reservation_order.get( + reservation_order_id="str", + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_order_begin_purchase(self, resource_group): + response = await ( + await self.client.reservation_order.begin_purchase( + reservation_order_id="str", + body={ + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_order_list(self, resource_group): + response = self.client.reservation_order.list( + api_version="2022-11-01", + ) + 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_order_change_directory(self, resource_group): + response = await self.client.reservation_order.change_directory( + reservation_order_id="str", + body={"destinationTenantId": "str"}, + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_reservation_order_calculate(self, resource_group): + response = await self.client.reservation_order.calculate( + body={ + "location": "str", + "properties": { + "appliedScopeProperties": { + "displayName": "str", + "managementGroupId": "str", + "resourceGroupId": "str", + "subscriptionId": "str", + "tenantId": "str", + }, + "appliedScopeType": "str", + "appliedScopes": ["str"], + "billingPlan": "str", + "billingScopeId": "str", + "displayName": "str", + "quantity": 0, + "renew": bool, + "reservedResourceProperties": {"instanceFlexibility": "str"}, + "reservedResourceType": "str", + "reviewDateTime": "2020-02-20 00:00:00", + "term": "str", + }, + "sku": {"name": "str"}, + }, + api_version="2022-11-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_operations.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_operations.py new file mode 100644 index 000000000000..136b2891b23b --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_operations.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.reservations import ReservationsMgmtClient + +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 TestReservationsMgmtReturnOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_return_operations_begin_post(self, resource_group): + response = self.client.return_operations.begin_post( + reservation_order_id="str", + body={ + "properties": { + "reservationToReturn": {"quantity": 0, "reservationId": "str"}, + "returnReason": "str", + "scope": "str", + "sessionId": "str", + } + }, + api_version="2022-11-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_operations_async.py b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_operations_async.py new file mode 100644 index 000000000000..f8c1bd41d13d --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/generated_tests/test_reservations_mgmt_return_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.reservations.aio import ReservationsMgmtClient + +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 TestReservationsMgmtReturnOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_return_operations_begin_post(self, resource_group): + response = await ( + await self.client.return_operations.begin_post( + reservation_order_id="str", + body={ + "properties": { + "reservationToReturn": {"quantity": 0, "reservationId": "str"}, + "returnReason": "str", + "scope": "str", + "sessionId": "str", + } + }, + api_version="2022-11-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... diff --git a/sdk/reservations/azure-mgmt-reservations/pyproject.toml b/sdk/reservations/azure-mgmt-reservations/pyproject.toml index 540da07d41af..5965fd23cd18 100644 --- a/sdk/reservations/azure-mgmt-reservations/pyproject.toml +++ b/sdk/reservations/azure-mgmt-reservations/pyproject.toml @@ -1,6 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-reservations" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Reservations 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.reservations._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-reservations" +package_pprint_name = "Reservations" +package_doc_id = "" +is_stable = false +title = "AzureReservationAPI" +package_nspkg = "azure-mgmt-nspkg" +is_arm = true +need_msrestazure = false +need_azuremgmtcore = true +sample_link = "" +exclude_folders = "" diff --git a/sdk/reservations/azure-mgmt-reservations/sdk_packaging.toml b/sdk/reservations/azure-mgmt-reservations/sdk_packaging.toml deleted file mode 100644 index de6ccd6be366..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/sdk_packaging.toml +++ /dev/null @@ -1,6 +0,0 @@ -[packaging] -package_name = "azure-mgmt-reservations" -package_pprint_name = "Reservations" -package_doc_id = "" -is_stable = false -title = "AzureReservationAPI" diff --git a/sdk/reservations/azure-mgmt-reservations/setup.py b/sdk/reservations/azure-mgmt-reservations/setup.py deleted file mode 100644 index 7aaa79b31161..000000000000 --- a/sdk/reservations/azure-mgmt-reservations/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-reservations" -PACKAGE_PPRINT_NAME = "Reservations" - -# 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/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py b/sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py index 6d2f7835f487..1f1ca82af642 100644 --- a/sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py +++ b/sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py @@ -3,17 +3,13 @@ from azure.mgmt.reservations import AzureReservationAPI from azure.mgmt.reservations.models import * from devtools_testutils import AzureMgmtRecordedTestCase -from azure.mgmt.reservations.models import ( - ReservedResourceType, - InstanceFlexibility, - AppliedScopeType -) +from azure.mgmt.reservations.models import ReservedResourceType, InstanceFlexibility, AppliedScopeType import unittest - # change the custom endpoint to set the environment _CUSTOM_ENDPOINT = "https://api-dogfood.resources.windows-int.net/" + @pytest.mark.skip("skip test") class TestMgmtReservations(AzureMgmtRecordedTestCase): @@ -55,7 +51,8 @@ def _create_purchase_request(self): display_name="TestPythonPurchase", applied_scope_type="Single", applied_scopes=["/subscriptions/{}".format(self.settings.SUBSCRIPTION_ID)], - reserved_resource_properties=PurchaseRequestPropertiesReservedResourceProperties(instance_flexibility="On")) + reserved_resource_properties=PurchaseRequestPropertiesReservedResourceProperties(instance_flexibility="On"), + ) def _calculate_reservation_order(self): purchase_request = self._create_purchase_request() @@ -78,13 +75,19 @@ def _test_reservation_get(self, reservation_order_id, reservation_id): self._validate_reservation(reservation) def _test_update_reservation_to_shared(self, reservation_order_id, reservation_id): - patch = Patch(applied_scope_type=AppliedScopeType.shared, applied_scopes=None, instance_flexibility=InstanceFlexibility.on) + patch = Patch( + applied_scope_type=AppliedScopeType.shared, applied_scopes=None, instance_flexibility=InstanceFlexibility.on + ) reservation = self.reservation_client.reservation.update(reservation_order_id, reservation_id, patch).result() self._validate_reservation(reservation) def _test_update_reservation_to_single(self, reservation_order_id, reservation_id): scope = ["/subscriptions/{}".format(self.settings.SUBSCRIPTION_ID)] - patch = Patch(applied_scope_type=AppliedScopeType.single, applied_scopes=scope, instance_flexibility=InstanceFlexibility.on) + patch = Patch( + applied_scope_type=AppliedScopeType.single, + applied_scopes=scope, + instance_flexibility=InstanceFlexibility.on, + ) reservation = self.reservation_client.reservation.update(reservation_order_id, reservation_id, patch).result() self._validate_reservation(reservation) @@ -93,9 +96,13 @@ def _test_split(self, reservation_order_id, reservation_id): for reservation in reservation_list: if "Succeeded" in reservation.properties.provisioning_state: reservation_to_update = reservation - split_reservation_id = reservation_to_update.id.split('/')[6] - reservation_id = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format(reservation_order_id, split_reservation_id) - split_response = self.reservation_client.reservation.split(reservation_order_id, [1, 1], reservation_id).result() + split_reservation_id = reservation_to_update.id.split("/")[6] + reservation_id = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( + reservation_order_id, split_reservation_id + ) + split_response = self.reservation_client.reservation.split( + reservation_order_id, [1, 1], reservation_id + ).result() split_quantity = 0 for reservation in split_response: @@ -111,13 +118,19 @@ def _test_merge(self, reservation_order_id): for reservation in reservation_list: if "Succeeded" in reservation.properties.provisioning_state: if split_id1 is None: - split_id1 = reservation.id.split('/')[6] + split_id1 = reservation.id.split("/")[6] else: - split_id2 = reservation.id.split('/')[6] - merge_id1 = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format(reservation_order_id, split_id1) - merge_id2 = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format(reservation_order_id, split_id2) - merge_response = self.reservation_client.reservation.merge(reservation_order_id, [merge_id1, merge_id2]).result() - + split_id2 = reservation.id.split("/")[6] + merge_id1 = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( + reservation_order_id, split_id1 + ) + merge_id2 = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( + reservation_order_id, split_id2 + ) + merge_response = self.reservation_client.reservation.merge( + reservation_order_id, [merge_id1, merge_id2] + ).result() + merge_quantity = 0 for reservation in merge_response: self._validate_reservation(reservation) @@ -155,26 +168,32 @@ def test_reservation_operations(self): def test_reservation_order_list(self): reservation_order_list = self.reservation_client.reservation_order.list() self.assertIsNotNone(reservation_order_list) - self.assertTrue(len(reservation_order_list._attribute_map['current_page']) > 0) + self.assertTrue(len(reservation_order_list._attribute_map["current_page"]) > 0) for reservation_order in reservation_order_list: self._validate_reservation_order(reservation_order) def test_get_catalog(self): - catalog_items = self.reservation_client.get_catalog(self.settings.SUBSCRIPTION_ID, ReservedResourceType.virtual_machines, "westus") + catalog_items = self.reservation_client.get_catalog( + self.settings.SUBSCRIPTION_ID, ReservedResourceType.virtual_machines, "westus" + ) for item in catalog_items: self.assertIsNotNone(item.resource_type) self.assertIsNotNone(item.name) self.assertTrue(len(item.terms) > 0) self.assertTrue(len(item.locations) > 0) self.assertTrue(len(item.sku_properties) > 0) - catalog_items = self.reservation_client.get_catalog(self.settings.SUBSCRIPTION_ID, ReservedResourceType.sql_databases, "southeastasia") + catalog_items = self.reservation_client.get_catalog( + self.settings.SUBSCRIPTION_ID, ReservedResourceType.sql_databases, "southeastasia" + ) for item in catalog_items: self.assertIsNotNone(item.resource_type) self.assertIsNotNone(item.name) self.assertTrue(len(item.terms) > 0) self.assertTrue(len(item.locations) > 0) self.assertTrue(len(item.sku_properties) > 0) - catalog_items = self.reservation_client.get_catalog(self.settings.SUBSCRIPTION_ID, ReservedResourceType.suse_linux) + catalog_items = self.reservation_client.get_catalog( + self.settings.SUBSCRIPTION_ID, ReservedResourceType.suse_linux + ) for item in catalog_items: self.assertIsNotNone(item.resource_type) self.assertIsNotNone(item.name) @@ -183,7 +202,9 @@ def test_get_catalog(self): def test_applied_reservation(self): applied_reservation = self.reservation_client.get_applied_reservation_list(self.settings.SUBSCRIPTION_ID) - expected_id = "/subscriptions/{}/providers/microsoft.capacity/AppliedReservations/default".format(self.settings.SUBSCRIPTION_ID) + expected_id = "/subscriptions/{}/providers/microsoft.capacity/AppliedReservations/default".format( + self.settings.SUBSCRIPTION_ID + ) self.assertEqual(expected_id, applied_reservation.id) self.assertEqual("default", applied_reservation.name) self.assertEqual("Microsoft.Capacity/AppliedReservations", applied_reservation.type) @@ -196,6 +217,7 @@ def test_get_operation(self): self.assertIsNotNone(operation.name) self.assertIsNotNone(operation.display) -#------------------------------------------------------------------------------ -if __name__ == '__main__': + +# ------------------------------------------------------------------------------ +if __name__ == "__main__": unittest.main() diff --git a/sdk/reservations/azure-mgmt-reservations/tsp-location.yaml b/sdk/reservations/azure-mgmt-reservations/tsp-location.yaml new file mode 100644 index 000000000000..5c590808d68a --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/reservations/resource-manager/Microsoft.Capacity/Reservations +commit: cb62053a18882dd258d9922be9770702b7ef6ac9 +repo: Azure/azure-rest-api-specs +additionalDirectories: From 7c2d055be896751ed08887875f093691d85f222e Mon Sep 17 00:00:00 2001 From: "Chenxi Jiang (WICRESOFT NORTH AMERICA LTD)" Date: Mon, 1 Jun 2026 15:05:43 +0800 Subject: [PATCH 2/6] Add live tests and optimize CHANGELOG for azure-mgmt-reservations Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure-mgmt-reservations/CHANGELOG.md | 61 +++--------- .../azure-mgmt-reservations/tests/conftest.py | 46 ++++++++++ .../tests/test_mgmt_reservations.py | 92 ++++++++++++++----- .../tests/test_operation_operations_test.py | 24 +++++ 4 files changed, 151 insertions(+), 72 deletions(-) create mode 100644 sdk/reservations/azure-mgmt-reservations/tests/conftest.py create mode 100644 sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_test.py diff --git a/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md b/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md index a53ababa5ae2..a96866f4c909 100644 --- a/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md +++ b/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md @@ -5,74 +5,39 @@ ### Features Added - Model `CurrentQuotaLimitBase` added property `system_data` - - Model `QuotaRequestDetails` added property `properties` - Model `QuotaRequestDetails` added property `system_data` - - Model `ReservationOrderResponse` added property `properties` - - Model `SkuRestriction` added property `values_property` - - Added model `MergeProperties` - - Added model `PatchProperties` - - Added model `ReservationOrderProperties` - - Added model `SplitProperties` ### 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. - Deleted or renamed model `AzureReservationAPI` - - Model `MergeRequest` deleted or renamed its instance variable `sources` - - Model `Patch` deleted or renamed its instance variable `applied_scope_type` - - Model `Patch` deleted or renamed its instance variable `applied_scopes` - - Model `Patch` deleted or renamed its instance variable `applied_scope_properties` - - Model `Patch` deleted or renamed its instance variable `instance_flexibility` - - Model `Patch` deleted or renamed its instance variable `name` - - Model `Patch` deleted or renamed its instance variable `renew` - - Model `Patch` deleted or renamed its instance variable `renew_properties` - - Model `Patch` deleted or renamed its instance variable `review_date_time` - - Model `QuotaRequestDetails` deleted or renamed its instance variable `provisioning_state` - - Model `QuotaRequestDetails` deleted or renamed its instance variable `message` - - Model `QuotaRequestDetails` deleted or renamed its instance variable `request_submit_time` - - Model `QuotaRequestDetails` deleted or renamed its instance variable `value` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `display_name` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `request_date_time` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `created_date_time` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `expiry_date` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `expiry_date_time` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `benefit_start_time` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `original_quantity` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `term` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `provisioning_state` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `billing_plan` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `plan_information` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `reservations` - - Model `ReservationOrderResponse` deleted or renamed its instance variable `review_date_time` - - Model `SkuRestriction` deleted or renamed its instance variable `values` - - Model `SplitRequest` deleted or renamed its instance variable `quantities` - - Model `SplitRequest` deleted or renamed its instance variable `reservation_id` - - Deleted or renamed model `CatalogsResult` + - Model `MergeRequest` moved instance variable `sources` under property `properties` whose type is `MergeProperties` + - Model `Patch` moved instance variable `applied_scope_type`, `applied_scopes`, `applied_scope_properties`, `instance_flexibility`, `name`, `renew`, `renew_properties` and `review_date_time` under property `properties` whose type is `PatchProperties` + - Model `QuotaRequestDetails` moved instance variable `provisioning_state`, `message`, `request_submit_time` and `value` under property `properties` whose type is `QuotaRequestProperties` + - Model `ReservationOrderResponse` moved instance variable `display_name`, `request_date_time`, `created_date_time`, `expiry_date`, `expiry_date_time`, `benefit_start_time`, `original_quantity`, `term`, `provisioning_state`, `billing_plan`, `plan_information`, `reservations` and `review_date_time` under property `properties` whose type is `ReservationOrderProperties` + - Model `SkuRestriction` renamed its instance variable `values` to `values_property` + - Model `SplitRequest` moved instance variable `quantities` and `reservation_id` under property `properties` whose type is `SplitProperties` - Deleted or renamed model `CreateGenericQuotaRequestParameters` - Deleted or renamed model `CurrentQuotaLimit` - Deleted or renamed model `DisplayProvisioningState` - Deleted or renamed model `Location` - - Deleted or renamed model `OperationList` - - Deleted or renamed model `QuotaLimits` - - Deleted or renamed model `QuotaLimitsResponse` - - Deleted or renamed model `QuotaRequestDetailsList` - Deleted or renamed model `QuotaRequestOneResourceSubmitResponse` - Deleted or renamed model `QuotaRequestSubmitResponse` - Deleted or renamed model `QuotaRequestSubmitResponse201` - Deleted or renamed model `RefundResponse` - - Deleted or renamed model `ReservationList` - - Deleted or renamed model `ReservationOrderList` - Deleted or renamed model `UserFriendlyAppliedScopeType` - Deleted or renamed model `UserFriendlyRenewState` - Method `QuotaRequestStatusOperations.list` changed its parameter `skiptoken` from `positional_or_keyword` to `keyword_only` - Method `ReservationOperations.get` changed its parameter `expand` from `positional_or_keyword` to `keyword_only` - - Method `ReservationOperations.list_all` changed its parameter `orderby` from `positional_or_keyword` to `keyword_only` - - Method `ReservationOperations.list_all` changed its parameter `refresh_summary` from `positional_or_keyword` to `keyword_only` - - Method `ReservationOperations.list_all` changed its parameter `skiptoken` from `positional_or_keyword` to `keyword_only` - - Method `ReservationOperations.list_all` changed its parameter `selected_state` from `positional_or_keyword` to `keyword_only` - - Method `ReservationOperations.list_all` changed its parameter `take` from `positional_or_keyword` to `keyword_only` + - Method `ReservationOperations.list_all` changed its parameter `orderby`/`refresh_summary`/`skiptoken`/`selected_state`/`take` from `positional_or_keyword` to `keyword_only` - Method `ReservationOrderOperations.get` changed its parameter `expand` from `positional_or_keyword` to `keyword_only` - Deleted or renamed model `AzureReservationAPIOperationsMixin` +### Other Changes + + - Deleted model `CatalogsResult`/`OperationList`/`QuotaLimits`/`QuotaLimitsResponse`/`QuotaRequestDetailsList`/`ReservationList`/`ReservationOrderList` which actually were not used by SDK users + ## 2.3.0 (2023-03-20) ### Features Added diff --git a/sdk/reservations/azure-mgmt-reservations/tests/conftest.py b/sdk/reservations/azure-mgmt-reservations/tests/conftest.py new file mode 100644 index 000000000000..1a68fa99701a --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/tests/conftest.py @@ -0,0 +1,46 @@ +# coding=utf-8 +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() + + +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + reservationsmgmt_subscription_id = os.environ.get( + "AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + reservationsmgmt_tenant_id = os.environ.get( + "AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000" + ) + reservationsmgmt_client_id = os.environ.get( + "AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000" + ) + reservationsmgmt_client_secret = os.environ.get( + "AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=reservationsmgmt_subscription_id, + value="00000000-0000-0000-0000-000000000000", + ) + add_general_regex_sanitizer( + regex=reservationsmgmt_tenant_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=reservationsmgmt_client_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=reservationsmgmt_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/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py b/sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py index 1f1ca82af642..6c61e7018497 100644 --- a/sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py +++ b/sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py @@ -3,7 +3,11 @@ from azure.mgmt.reservations import AzureReservationAPI from azure.mgmt.reservations.models import * from devtools_testutils import AzureMgmtRecordedTestCase -from azure.mgmt.reservations.models import ReservedResourceType, InstanceFlexibility, AppliedScopeType +from azure.mgmt.reservations.models import ( + ReservedResourceType, + InstanceFlexibility, + AppliedScopeType, +) import unittest # change the custom endpoint to set the environment @@ -14,7 +18,9 @@ class TestMgmtReservations(AzureMgmtRecordedTestCase): def setup_method(self, _): - self.reservation_client = self.create_basic_client(AzureReservationAPI, base_url=_CUSTOM_ENDPOINT) + self.reservation_client = self.create_basic_client( + AzureReservationAPI, base_url=_CUSTOM_ENDPOINT + ) # self.reservation_client = self.create_basic_client(AzureReservationAPI) def _validate_reservation_order(self, reservation_order): @@ -51,34 +57,48 @@ def _create_purchase_request(self): display_name="TestPythonPurchase", applied_scope_type="Single", applied_scopes=["/subscriptions/{}".format(self.settings.SUBSCRIPTION_ID)], - reserved_resource_properties=PurchaseRequestPropertiesReservedResourceProperties(instance_flexibility="On"), + reserved_resource_properties=PurchaseRequestPropertiesReservedResourceProperties( + instance_flexibility="On" + ), ) def _calculate_reservation_order(self): purchase_request = self._create_purchase_request() - calculate_response = self.reservation_client.reservation_order.calculate(purchase_request) + calculate_response = self.reservation_client.reservation_order.calculate( + purchase_request + ) return calculate_response.properties.reservation_order_id def _purchase_reservation_order(self, reservation_order_id): purchase_request = self._create_purchase_request() - self.reservation_client.reservation_order.purchase(reservation_order_id, purchase_request).result() + self.reservation_client.reservation_order.purchase( + reservation_order_id, purchase_request + ).result() def _test_reservation_order_get(self, reservation_order_id): - reservation_order = self.reservation_client.reservation_order.get(reservation_order_id) + reservation_order = self.reservation_client.reservation_order.get( + reservation_order_id + ) self.assertIsNotNone(reservation_order) self._validate_reservation_order(reservation_order) return reservation_order def _test_reservation_get(self, reservation_order_id, reservation_id): - reservation = self.reservation_client.reservation.get(reservation_id, reservation_order_id) + reservation = self.reservation_client.reservation.get( + reservation_id, reservation_order_id + ) self._validate_reservation(reservation) def _test_update_reservation_to_shared(self, reservation_order_id, reservation_id): patch = Patch( - applied_scope_type=AppliedScopeType.shared, applied_scopes=None, instance_flexibility=InstanceFlexibility.on + applied_scope_type=AppliedScopeType.shared, + applied_scopes=None, + instance_flexibility=InstanceFlexibility.on, ) - reservation = self.reservation_client.reservation.update(reservation_order_id, reservation_id, patch).result() + reservation = self.reservation_client.reservation.update( + reservation_order_id, reservation_id, patch + ).result() self._validate_reservation(reservation) def _test_update_reservation_to_single(self, reservation_order_id, reservation_id): @@ -88,17 +108,23 @@ def _test_update_reservation_to_single(self, reservation_order_id, reservation_i applied_scopes=scope, instance_flexibility=InstanceFlexibility.on, ) - reservation = self.reservation_client.reservation.update(reservation_order_id, reservation_id, patch).result() + reservation = self.reservation_client.reservation.update( + reservation_order_id, reservation_id, patch + ).result() self._validate_reservation(reservation) def _test_split(self, reservation_order_id, reservation_id): - reservation_list = self.reservation_client.reservation.list(reservation_order_id) + reservation_list = self.reservation_client.reservation.list( + reservation_order_id + ) for reservation in reservation_list: if "Succeeded" in reservation.properties.provisioning_state: reservation_to_update = reservation split_reservation_id = reservation_to_update.id.split("/")[6] - reservation_id = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( - reservation_order_id, split_reservation_id + reservation_id = ( + "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( + reservation_order_id, split_reservation_id + ) ) split_response = self.reservation_client.reservation.split( reservation_order_id, [1, 1], reservation_id @@ -112,7 +138,9 @@ def _test_split(self, reservation_order_id, reservation_id): self.assertTrue(split_quantity == 2) def _test_merge(self, reservation_order_id): - reservation_list = self.reservation_client.reservation.list(reservation_order_id) + reservation_list = self.reservation_client.reservation.list( + reservation_order_id + ) split_id1 = None split_id2 = None for reservation in reservation_list: @@ -121,11 +149,15 @@ def _test_merge(self, reservation_order_id): split_id1 = reservation.id.split("/")[6] else: split_id2 = reservation.id.split("/")[6] - merge_id1 = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( - reservation_order_id, split_id1 + merge_id1 = ( + "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( + reservation_order_id, split_id1 + ) ) - merge_id2 = "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( - reservation_order_id, split_id2 + merge_id2 = ( + "/providers/Microsoft.Capacity/reservationOrders/{}/reservations/{}".format( + reservation_order_id, split_id2 + ) ) merge_response = self.reservation_client.reservation.merge( reservation_order_id, [merge_id1, merge_id2] @@ -139,12 +171,16 @@ def _test_merge(self, reservation_order_id): self.assertTrue(merge_quantity == 2) def _test_reservation_history_list(self, reservation_order_id, reservation_id): - reservation_history = self.reservation_client.reservation.list_revisions(reservation_id, reservation_order_id) + reservation_history = self.reservation_client.reservation.list_revisions( + reservation_id, reservation_order_id + ) for reservation in reservation_history: self._validate_reservation(reservation) def _test_reservation_list(self, reservation_order_id): - reservation_list = self.reservation_client.reservation.list(reservation_order_id) + reservation_list = self.reservation_client.reservation.list( + reservation_order_id + ) for reservation in reservation_list: self._validate_reservation(reservation) @@ -174,7 +210,9 @@ def test_reservation_order_list(self): def test_get_catalog(self): catalog_items = self.reservation_client.get_catalog( - self.settings.SUBSCRIPTION_ID, ReservedResourceType.virtual_machines, "westus" + self.settings.SUBSCRIPTION_ID, + ReservedResourceType.virtual_machines, + "westus", ) for item in catalog_items: self.assertIsNotNone(item.resource_type) @@ -183,7 +221,9 @@ def test_get_catalog(self): self.assertTrue(len(item.locations) > 0) self.assertTrue(len(item.sku_properties) > 0) catalog_items = self.reservation_client.get_catalog( - self.settings.SUBSCRIPTION_ID, ReservedResourceType.sql_databases, "southeastasia" + self.settings.SUBSCRIPTION_ID, + ReservedResourceType.sql_databases, + "southeastasia", ) for item in catalog_items: self.assertIsNotNone(item.resource_type) @@ -201,13 +241,17 @@ def test_get_catalog(self): self.assertTrue(len(item.sku_properties) > 0) def test_applied_reservation(self): - applied_reservation = self.reservation_client.get_applied_reservation_list(self.settings.SUBSCRIPTION_ID) + applied_reservation = self.reservation_client.get_applied_reservation_list( + self.settings.SUBSCRIPTION_ID + ) expected_id = "/subscriptions/{}/providers/microsoft.capacity/AppliedReservations/default".format( self.settings.SUBSCRIPTION_ID ) self.assertEqual(expected_id, applied_reservation.id) self.assertEqual("default", applied_reservation.name) - self.assertEqual("Microsoft.Capacity/AppliedReservations", applied_reservation.type) + self.assertEqual( + "Microsoft.Capacity/AppliedReservations", applied_reservation.type + ) for order_id in applied_reservation.reservation_order_ids.value: self.assertIn("/providers/Microsoft.Capacity/reservationorders/", order_id) diff --git a/sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_test.py b/sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_test.py new file mode 100644 index 000000000000..5dac1329558d --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_test.py @@ -0,0 +1,24 @@ +# coding=utf-8 +import pytest +from azure.mgmt.reservations import ReservationsMgmtClient + +from devtools_testutils import ( + AzureMgmtRecordedTestCase, + RandomNameResourceGroupPreparer, + recorded_by_proxy, +) + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestReservationsMgmtOperationOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operation_list(self, resource_group): + response = self.client.operation.list() + result = [r for r in response] + assert len(result) From 3ae92d6f0bfbe56883cb420afc9be20d51d06e4f Mon Sep 17 00:00:00 2001 From: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> Date: Mon, 1 Jun 2026 15:14:21 +0800 Subject: [PATCH 3/6] Update CHANGELOG.md --- sdk/reservations/azure-mgmt-reservations/CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md b/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md index a96866f4c909..e558635beb5c 100644 --- a/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md +++ b/sdk/reservations/azure-mgmt-reservations/CHANGELOG.md @@ -11,7 +11,7 @@ - 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. - - Deleted or renamed model `AzureReservationAPI` + - Renamed client name `AzureReservationAPI` to `ReservationsMgmtClient` - Model `MergeRequest` moved instance variable `sources` under property `properties` whose type is `MergeProperties` - Model `Patch` moved instance variable `applied_scope_type`, `applied_scopes`, `applied_scope_properties`, `instance_flexibility`, `name`, `renew`, `renew_properties` and `review_date_time` under property `properties` whose type is `PatchProperties` - Model `QuotaRequestDetails` moved instance variable `provisioning_state`, `message`, `request_submit_time` and `value` under property `properties` whose type is `QuotaRequestProperties` @@ -32,7 +32,7 @@ - Method `ReservationOperations.get` changed its parameter `expand` from `positional_or_keyword` to `keyword_only` - Method `ReservationOperations.list_all` changed its parameter `orderby`/`refresh_summary`/`skiptoken`/`selected_state`/`take` from `positional_or_keyword` to `keyword_only` - Method `ReservationOrderOperations.get` changed its parameter `expand` from `positional_or_keyword` to `keyword_only` - - Deleted or renamed model `AzureReservationAPIOperationsMixin` + - Renamed operation group `AzureReservationAPIOperationsMixin` to `_ReservationsMgmtClientOperationsMixin` ### Other Changes From 1e9e954fe6d8b08c27f3cf24ab4887b6f4612595 Mon Sep 17 00:00:00 2001 From: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> Date: Mon, 1 Jun 2026 15:14:39 +0800 Subject: [PATCH 4/6] Update dev_requirements.txt --- sdk/reservations/azure-mgmt-reservations/dev_requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/reservations/azure-mgmt-reservations/dev_requirements.txt b/sdk/reservations/azure-mgmt-reservations/dev_requirements.txt index b18a83fbb955..a4eaf63f2d63 100644 --- a/sdk/reservations/azure-mgmt-reservations/dev_requirements.txt +++ b/sdk/reservations/azure-mgmt-reservations/dev_requirements.txt @@ -1 +1,2 @@ --e ../../../eng/tools/azure-sdk-tools \ No newline at end of file +-e ../../../eng/tools/azure-sdk-tools +aiohttp From f0c54b75b4dbc19116ffcdf2dc8ab3db146d698c Mon Sep 17 00:00:00 2001 From: ChenxiJiang333 <119990644+ChenxiJiang333@users.noreply.github.com> Date: Mon, 1 Jun 2026 16:49:15 +0800 Subject: [PATCH 5/6] Rename test_mgmt_reservations.py to disable_test_mgmt_reservations.py --- ...est_mgmt_reservations.py => disable_test_mgmt_reservations.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename sdk/reservations/azure-mgmt-reservations/tests/{test_mgmt_reservations.py => disable_test_mgmt_reservations.py} (100%) diff --git a/sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py b/sdk/reservations/azure-mgmt-reservations/tests/disable_test_mgmt_reservations.py similarity index 100% rename from sdk/reservations/azure-mgmt-reservations/tests/test_mgmt_reservations.py rename to sdk/reservations/azure-mgmt-reservations/tests/disable_test_mgmt_reservations.py From 4ca5f73aa7b8b2048d17a201cb19853a416f375f Mon Sep 17 00:00:00 2001 From: "Chenxi Jiang (WICRESOFT NORTH AMERICA LTD)" Date: Mon, 1 Jun 2026 16:50:44 +0800 Subject: [PATCH 6/6] Add async live test for azure-mgmt-reservations Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../test_operation_operations_async_test.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_async_test.py diff --git a/sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_async_test.py b/sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_async_test.py new file mode 100644 index 000000000000..75471a65f320 --- /dev/null +++ b/sdk/reservations/azure-mgmt-reservations/tests/test_operation_operations_async_test.py @@ -0,0 +1,24 @@ +# coding=utf-8 +import pytest +from azure.mgmt.reservations.aio import ReservationsMgmtClient + +from devtools_testutils import ( + AzureMgmtRecordedTestCase, + RandomNameResourceGroupPreparer, +) +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.live_test_only +class TestReservationsMgmtOperationOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(ReservationsMgmtClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operation_list(self, resource_group): + response = self.client.operation.list() + result = [r async for r in response] + assert len(result)