diff --git a/sdk/redis/azure-mgmt-redis/CHANGELOG.md b/sdk/redis/azure-mgmt-redis/CHANGELOG.md index a314aa761491..edf93e70a0d2 100644 --- a/sdk/redis/azure-mgmt-redis/CHANGELOG.md +++ b/sdk/redis/azure-mgmt-redis/CHANGELOG.md @@ -1,5 +1,46 @@ # Release History +## 15.0.0b1 (2026-05-22) + +### Features Added + + - Client `RedisManagementClient` added parameter `cloud_setting` in method `__init__` + - Client `RedisManagementClient` added method `send_request` + - Model `PrivateEndpointConnection` added property `system_data` + - Model `PrivateLinkResource` added property `system_data` + - Enum `ProvisioningState` added member `MIGRATING` + - Enum `ProvisioningState` added member `MIGRATION_CANCELLATION_FAILED` + - Enum `ProvisioningState` added member `MIGRATION_CANCELLING` + - Enum `ProvisioningState` added member `MIGRATION_FAILED` + - Enum `ProvisioningState` added member `MIGRATION_SUCCEEDED` + - Model `ProxyResource` added property `system_data` + - Model `RedisCacheAccessPolicy` added property `system_data` + - Model `RedisCacheAccessPolicyAssignment` added property `system_data` + - Model `RedisFirewallRule` added property `system_data` + - Model `RedisLinkedServerWithProperties` added property `system_data` + - Model `RedisPatchSchedule` added property `system_data` + - Model `RedisProperties` added property `target_amr_resource_id` + - Model `RedisResource` added property `system_data` + - Model `Resource` added property `system_data` + - Model `TrackedResource` added property `system_data` + - Added enum `CreatedByType` + - Added model `SystemData` + +### 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. + - Model `RedisCreateParameters` moved instance variable `redis_configuration`, `redis_version`, `enable_non_ssl_port`, `replicas_per_master`, `replicas_per_primary`, `tenant_settings`, `shard_count`, `minimum_tls_version`, `public_network_access`, `update_channel`, `disable_access_key_authentication`, `zonal_allocation_policy`, `sku`, `subnet_id` and `static_ip` under property `properties` whose type is `RedisCreateProperties` + - Model `RedisLinkedServerCreateParameters` moved instance variable `linked_redis_cache_id`, `linked_redis_cache_location`, `server_role`, `geo_replicated_primary_host_name` and `primary_host_name` under property `properties` whose type is `RedisLinkedServerCreateProperties` + - Model `RedisLinkedServerWithProperties` moved instance variable `linked_redis_cache_id`, `linked_redis_cache_location`, `server_role`, `geo_replicated_primary_host_name`, `primary_host_name` and `provisioning_state` under property `properties` whose type is `RedisLinkedServerProperties` + - Model `RedisPatchSchedule` moved instance variable `schedule_entries` under property `properties` whose type is `ScheduleEntries` + - Model `RedisResource` moved instance variable `redis_configuration`, `redis_version`, `enable_non_ssl_port`, `replicas_per_master`, `replicas_per_primary`, `tenant_settings`, `shard_count`, `minimum_tls_version`, `public_network_access`, `update_channel`, `disable_access_key_authentication`, `zonal_allocation_policy`, `sku`, `subnet_id`, `static_ip`, `provisioning_state`, `host_name`, `port`, `ssl_port`, `access_keys`, `linked_servers`, `instances` and `private_endpoint_connections` under property `properties` whose type is `RedisProperties` + - Model `RedisUpdateParameters` moved instance variable `redis_configuration`, `redis_version`, `enable_non_ssl_port`, `replicas_per_master`, `replicas_per_primary`, `tenant_settings`, `shard_count`, `minimum_tls_version`, `public_network_access`, `update_channel`, `disable_access_key_authentication`, `zonal_allocation_policy` and `sku` under property `properties` whose type is `RedisUpdateProperties` + - Method `RedisOperations.list_upgrade_notifications` changed its parameter `history` from `positional_or_keyword` to `keyword_only` + +### Other Changes + + - Deleted model `NotificationListResponse`/`RedisCacheAccessPolicyAssignmentList`/`RedisCacheAccessPolicyList`/`RedisLinkedServerWithPropertiesList`/`RedisFirewallRuleCreateParameters` which actually were not used by SDK users + ## 14.5.0 (2025-01-20) ### Features Added diff --git a/sdk/redis/azure-mgmt-redis/MANIFEST.in b/sdk/redis/azure-mgmt-redis/MANIFEST.in index 8b3e09cd80af..92f4293e9212 100644 --- a/sdk/redis/azure-mgmt-redis/MANIFEST.in +++ b/sdk/redis/azure-mgmt-redis/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/redis/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py diff --git a/sdk/redis/azure-mgmt-redis/README.md b/sdk/redis/azure-mgmt-redis/README.md index 61408744a0ea..1b236e4e8aa0 100644 --- a/sdk/redis/azure-mgmt-redis/README.md +++ b/sdk/redis/azure-mgmt-redis/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Redis Cache Management Client Library. -This package has been tested with Python 3.8+. +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.8+ 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. diff --git a/sdk/redis/azure-mgmt-redis/_meta.json b/sdk/redis/azure-mgmt-redis/_meta.json deleted file mode 100644 index ec7865094253..000000000000 --- a/sdk/redis/azure-mgmt-redis/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "58740206b853320974ef5e4864f7be8120b15a27", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.10.2", - "use": [ - "@autorest/python@6.26.4", - "@autorest/modelerfour@4.27.0" - ], - "autorest_command": "autorest specification/redis/resource-manager/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.26.4 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", - "readme": "specification/redis/resource-manager/readme.md" -} \ No newline at end of file diff --git a/sdk/redis/azure-mgmt-redis/_metadata.json b/sdk/redis/azure-mgmt-redis/_metadata.json new file mode 100644 index 000000000000..23b73a38bfa0 --- /dev/null +++ b/sdk/redis/azure-mgmt-redis/_metadata.json @@ -0,0 +1,10 @@ +{ + "apiVersion": "2025-08-01-preview", + "apiVersions": { + "Microsoft.Cache": "2025-08-01-preview" + }, + "commit": "0ac0baaafaa117fd7296c0159ef2489d0461f86f", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/redis/resource-manager/Microsoft.Cache/Redis", + "emitterVersion": "0.62.1" +} \ No newline at end of file diff --git a/sdk/redis/azure-mgmt-redis/apiview-properties.json b/sdk/redis/azure-mgmt-redis/apiview-properties.json new file mode 100644 index 000000000000..3e7e87749e02 --- /dev/null +++ b/sdk/redis/azure-mgmt-redis/apiview-properties.json @@ -0,0 +1,158 @@ +{ + "CrossLanguagePackageId": "Microsoft.Cache", + "CrossLanguageDefinitionId": { + "azure.mgmt.redis.models.CheckNameAvailabilityParameters": "Microsoft.Cache.CheckNameAvailabilityParameters", + "azure.mgmt.redis.models.ErrorAdditionalInfo": "Azure.ResourceManager.CommonTypes.ErrorAdditionalInfo", + "azure.mgmt.redis.models.ErrorDetail": "Azure.ResourceManager.CommonTypes.ErrorDetail", + "azure.mgmt.redis.models.ErrorResponse": "Azure.ResourceManager.CommonTypes.ErrorResponse", + "azure.mgmt.redis.models.ExportRDBParameters": "Microsoft.Cache.ExportRDBParameters", + "azure.mgmt.redis.models.ImportRDBParameters": "Microsoft.Cache.ImportRDBParameters", + "azure.mgmt.redis.models.ManagedServiceIdentity": "Azure.ResourceManager.CommonTypes.ManagedServiceIdentity", + "azure.mgmt.redis.models.Operation": "Microsoft.Cache.Operation", + "azure.mgmt.redis.models.OperationDisplay": "Microsoft.Cache.OperationDisplay", + "azure.mgmt.redis.models.OperationStatusResult": "Azure.ResourceManager.CommonTypes.OperationStatusResult", + "azure.mgmt.redis.models.OperationStatus": "Microsoft.Cache.OperationStatus", + "azure.mgmt.redis.models.PrivateEndpoint": "Azure.ResourceManager.CommonTypes.PrivateEndpoint", + "azure.mgmt.redis.models.Resource": "Azure.ResourceManager.CommonTypes.Resource", + "azure.mgmt.redis.models.PrivateEndpointConnection": "Microsoft.Cache.PrivateEndpointConnection", + "azure.mgmt.redis.models.PrivateEndpointConnectionProperties": "Azure.ResourceManager.CommonTypes.PrivateEndpointConnectionProperties", + "azure.mgmt.redis.models.PrivateLinkResource": "Azure.ResourceManager.CommonTypes.PrivateLinkResource", + "azure.mgmt.redis.models.PrivateLinkResourceProperties": "Azure.ResourceManager.CommonTypes.PrivateLinkResourceProperties", + "azure.mgmt.redis.models.PrivateLinkServiceConnectionState": "Azure.ResourceManager.CommonTypes.PrivateLinkServiceConnectionState", + "azure.mgmt.redis.models.ProxyResource": "Azure.ResourceManager.CommonTypes.ProxyResource", + "azure.mgmt.redis.models.RedisAccessKeys": "Microsoft.Cache.RedisAccessKeys", + "azure.mgmt.redis.models.RedisCacheAccessPolicy": "Microsoft.Cache.RedisCacheAccessPolicy", + "azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment": "Microsoft.Cache.RedisCacheAccessPolicyAssignment", + "azure.mgmt.redis.models.RedisCacheAccessPolicyAssignmentProperties": "Microsoft.Cache.RedisCacheAccessPolicyAssignmentProperties", + "azure.mgmt.redis.models.RedisCacheAccessPolicyProperties": "Microsoft.Cache.RedisCacheAccessPolicyProperties", + "azure.mgmt.redis.models.RedisCommonProperties": "Microsoft.Cache.RedisCommonProperties", + "azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration": "Microsoft.Cache.RedisCommonPropertiesRedisConfiguration", + "azure.mgmt.redis.models.RedisCreateParameters": "Microsoft.Cache.RedisCreateParameters", + "azure.mgmt.redis.models.RedisCreateProperties": "Microsoft.Cache.RedisCreateProperties", + "azure.mgmt.redis.models.RedisFirewallRule": "Microsoft.Cache.RedisFirewallRule", + "azure.mgmt.redis.models.RedisFirewallRuleProperties": "Microsoft.Cache.RedisFirewallRuleProperties", + "azure.mgmt.redis.models.RedisForceRebootResponse": "Microsoft.Cache.RedisForceRebootResponse", + "azure.mgmt.redis.models.RedisInstanceDetails": "Microsoft.Cache.RedisInstanceDetails", + "azure.mgmt.redis.models.RedisLinkedServer": "Microsoft.Cache.RedisLinkedServer", + "azure.mgmt.redis.models.RedisLinkedServerCreateParameters": "Microsoft.Cache.RedisLinkedServerCreateParameters", + "azure.mgmt.redis.models.RedisLinkedServerCreateProperties": "Microsoft.Cache.RedisLinkedServerCreateProperties", + "azure.mgmt.redis.models.RedisLinkedServerProperties": "Microsoft.Cache.RedisLinkedServerProperties", + "azure.mgmt.redis.models.RedisLinkedServerWithProperties": "Microsoft.Cache.RedisLinkedServerWithProperties", + "azure.mgmt.redis.models.RedisPatchSchedule": "Microsoft.Cache.RedisPatchSchedule", + "azure.mgmt.redis.models.RedisProperties": "Microsoft.Cache.RedisProperties", + "azure.mgmt.redis.models.RedisRebootParameters": "Microsoft.Cache.RedisRebootParameters", + "azure.mgmt.redis.models.RedisRegenerateKeyParameters": "Microsoft.Cache.RedisRegenerateKeyParameters", + "azure.mgmt.redis.models.TrackedResource": "Azure.ResourceManager.CommonTypes.TrackedResource", + "azure.mgmt.redis.models.RedisResource": "Microsoft.Cache.RedisResource", + "azure.mgmt.redis.models.RedisUpdateParameters": "Microsoft.Cache.RedisUpdateParameters", + "azure.mgmt.redis.models.RedisUpdateProperties": "Microsoft.Cache.RedisUpdateProperties", + "azure.mgmt.redis.models.ScheduleEntries": "Microsoft.Cache.ScheduleEntries", + "azure.mgmt.redis.models.ScheduleEntry": "Microsoft.Cache.ScheduleEntry", + "azure.mgmt.redis.models.Sku": "Microsoft.Cache.Sku", + "azure.mgmt.redis.models.SystemData": "Azure.ResourceManager.CommonTypes.SystemData", + "azure.mgmt.redis.models.UpgradeNotification": "Microsoft.Cache.UpgradeNotification", + "azure.mgmt.redis.models.UserAssignedIdentity": "Azure.ResourceManager.CommonTypes.UserAssignedIdentity", + "azure.mgmt.redis.models.CreatedByType": "Azure.ResourceManager.CommonTypes.createdByType", + "azure.mgmt.redis.models.ReplicationRole": "Microsoft.Cache.ReplicationRole", + "azure.mgmt.redis.models.PrivateEndpointServiceConnectionStatus": "Azure.ResourceManager.CommonTypes.PrivateEndpointServiceConnectionStatus", + "azure.mgmt.redis.models.PrivateEndpointConnectionProvisioningState": "Azure.ResourceManager.CommonTypes.PrivateEndpointConnectionProvisioningState", + "azure.mgmt.redis.models.TlsVersion": "Microsoft.Cache.TlsVersion", + "azure.mgmt.redis.models.PublicNetworkAccess": "Microsoft.Cache.PublicNetworkAccess", + "azure.mgmt.redis.models.UpdateChannel": "Microsoft.Cache.UpdateChannel", + "azure.mgmt.redis.models.ZonalAllocationPolicy": "Microsoft.Cache.ZonalAllocationPolicy", + "azure.mgmt.redis.models.SkuName": "Microsoft.Cache.SkuName", + "azure.mgmt.redis.models.SkuFamily": "Microsoft.Cache.SkuFamily", + "azure.mgmt.redis.models.ProvisioningState": "Microsoft.Cache.ProvisioningState", + "azure.mgmt.redis.models.ManagedServiceIdentityType": "Azure.ResourceManager.CommonTypes.ManagedServiceIdentityType", + "azure.mgmt.redis.models.RedisKeyType": "Microsoft.Cache.RedisKeyType", + "azure.mgmt.redis.models.RebootType": "Microsoft.Cache.RebootType", + "azure.mgmt.redis.models.DayOfWeek": "Microsoft.Cache.DayOfWeek", + "azure.mgmt.redis.models.DefaultName": "Microsoft.Cache.DefaultName", + "azure.mgmt.redis.models.AccessPolicyProvisioningState": "Microsoft.Cache.AccessPolicyProvisioningState", + "azure.mgmt.redis.models.AccessPolicyType": "Microsoft.Cache.AccessPolicyType", + "azure.mgmt.redis.models.AccessPolicyAssignmentProvisioningState": "Microsoft.Cache.AccessPolicyAssignmentProvisioningState", + "azure.mgmt.redis.operations.Operations.list": "Azure.ResourceManager.Legacy.Operations.list", + "azure.mgmt.redis.aio.operations.Operations.list": "Azure.ResourceManager.Legacy.Operations.list", + "azure.mgmt.redis.operations.LinkedServerOperations.get": "Microsoft.Cache.LinkedServer.get", + "azure.mgmt.redis.aio.operations.LinkedServerOperations.get": "Microsoft.Cache.LinkedServer.get", + "azure.mgmt.redis.operations.LinkedServerOperations.begin_create": "Microsoft.Cache.LinkedServer.create", + "azure.mgmt.redis.aio.operations.LinkedServerOperations.begin_create": "Microsoft.Cache.LinkedServer.create", + "azure.mgmt.redis.operations.LinkedServerOperations.begin_delete": "Microsoft.Cache.LinkedServer.delete", + "azure.mgmt.redis.aio.operations.LinkedServerOperations.begin_delete": "Microsoft.Cache.LinkedServer.delete", + "azure.mgmt.redis.operations.LinkedServerOperations.list": "Microsoft.Cache.LinkedServer.list", + "azure.mgmt.redis.aio.operations.LinkedServerOperations.list": "Microsoft.Cache.LinkedServer.list", + "azure.mgmt.redis.operations.PrivateEndpointConnectionsOperations.get": "Microsoft.Cache.PrivateEndpointConnections.get", + "azure.mgmt.redis.aio.operations.PrivateEndpointConnectionsOperations.get": "Microsoft.Cache.PrivateEndpointConnections.get", + "azure.mgmt.redis.operations.PrivateEndpointConnectionsOperations.begin_put": "Microsoft.Cache.PrivateEndpointConnections.put", + "azure.mgmt.redis.aio.operations.PrivateEndpointConnectionsOperations.begin_put": "Microsoft.Cache.PrivateEndpointConnections.put", + "azure.mgmt.redis.operations.PrivateEndpointConnectionsOperations.delete": "Microsoft.Cache.PrivateEndpointConnections.delete", + "azure.mgmt.redis.aio.operations.PrivateEndpointConnectionsOperations.delete": "Microsoft.Cache.PrivateEndpointConnections.delete", + "azure.mgmt.redis.operations.PrivateEndpointConnectionsOperations.list": "Microsoft.Cache.PrivateEndpointConnections.list", + "azure.mgmt.redis.aio.operations.PrivateEndpointConnectionsOperations.list": "Microsoft.Cache.PrivateEndpointConnections.list", + "azure.mgmt.redis.operations.RedisOperations.get": "Microsoft.Cache.RedisResources.get", + "azure.mgmt.redis.aio.operations.RedisOperations.get": "Microsoft.Cache.RedisResources.get", + "azure.mgmt.redis.operations.RedisOperations.begin_create": "Microsoft.Cache.RedisResources.create", + "azure.mgmt.redis.aio.operations.RedisOperations.begin_create": "Microsoft.Cache.RedisResources.create", + "azure.mgmt.redis.operations.RedisOperations.begin_update": "Microsoft.Cache.RedisResources.update", + "azure.mgmt.redis.aio.operations.RedisOperations.begin_update": "Microsoft.Cache.RedisResources.update", + "azure.mgmt.redis.operations.RedisOperations.begin_delete": "Microsoft.Cache.RedisResources.delete", + "azure.mgmt.redis.aio.operations.RedisOperations.begin_delete": "Microsoft.Cache.RedisResources.delete", + "azure.mgmt.redis.operations.RedisOperations.list_by_resource_group": "Microsoft.Cache.RedisResources.listByResourceGroup", + "azure.mgmt.redis.aio.operations.RedisOperations.list_by_resource_group": "Microsoft.Cache.RedisResources.listByResourceGroup", + "azure.mgmt.redis.operations.RedisOperations.list_by_subscription": "Microsoft.Cache.RedisResources.listBySubscription", + "azure.mgmt.redis.aio.operations.RedisOperations.list_by_subscription": "Microsoft.Cache.RedisResources.listBySubscription", + "azure.mgmt.redis.operations.RedisOperations.list_upgrade_notifications": "Microsoft.Cache.RedisResources.listUpgradeNotifications", + "azure.mgmt.redis.aio.operations.RedisOperations.list_upgrade_notifications": "Microsoft.Cache.RedisResources.listUpgradeNotifications", + "azure.mgmt.redis.operations.RedisOperations.list_keys": "Microsoft.Cache.RedisResources.listKeys", + "azure.mgmt.redis.aio.operations.RedisOperations.list_keys": "Microsoft.Cache.RedisResources.listKeys", + "azure.mgmt.redis.operations.RedisOperations.regenerate_key": "Microsoft.Cache.RedisResources.regenerateKey", + "azure.mgmt.redis.aio.operations.RedisOperations.regenerate_key": "Microsoft.Cache.RedisResources.regenerateKey", + "azure.mgmt.redis.operations.RedisOperations.force_reboot": "Microsoft.Cache.RedisResources.forceReboot", + "azure.mgmt.redis.aio.operations.RedisOperations.force_reboot": "Microsoft.Cache.RedisResources.forceReboot", + "azure.mgmt.redis.operations.RedisOperations.begin_import_data": "Microsoft.Cache.RedisResources.importData", + "azure.mgmt.redis.aio.operations.RedisOperations.begin_import_data": "Microsoft.Cache.RedisResources.importData", + "azure.mgmt.redis.operations.RedisOperations.begin_export_data": "Microsoft.Cache.RedisResources.exportData", + "azure.mgmt.redis.aio.operations.RedisOperations.begin_export_data": "Microsoft.Cache.RedisResources.exportData", + "azure.mgmt.redis.operations.RedisOperations.begin_flush_cache": "Microsoft.Cache.RedisResources.flushCache", + "azure.mgmt.redis.aio.operations.RedisOperations.begin_flush_cache": "Microsoft.Cache.RedisResources.flushCache", + "azure.mgmt.redis.operations.RedisOperations.check_name_availability": "Microsoft.Cache.RedisOperationGroup.checkNameAvailability", + "azure.mgmt.redis.aio.operations.RedisOperations.check_name_availability": "Microsoft.Cache.RedisOperationGroup.checkNameAvailability", + "azure.mgmt.redis.operations.PrivateLinkResourcesOperations.list_by_redis_cache": "Microsoft.Cache.RedisResources.listByRedisCache", + "azure.mgmt.redis.aio.operations.PrivateLinkResourcesOperations.list_by_redis_cache": "Microsoft.Cache.RedisResources.listByRedisCache", + "azure.mgmt.redis.operations.FirewallRulesOperations.get": "Microsoft.Cache.RedisFirewallRules.get", + "azure.mgmt.redis.aio.operations.FirewallRulesOperations.get": "Microsoft.Cache.RedisFirewallRules.get", + "azure.mgmt.redis.operations.FirewallRulesOperations.create_or_update": "Microsoft.Cache.RedisFirewallRules.createOrUpdate", + "azure.mgmt.redis.aio.operations.FirewallRulesOperations.create_or_update": "Microsoft.Cache.RedisFirewallRules.createOrUpdate", + "azure.mgmt.redis.operations.FirewallRulesOperations.delete": "Microsoft.Cache.RedisFirewallRules.delete", + "azure.mgmt.redis.aio.operations.FirewallRulesOperations.delete": "Microsoft.Cache.RedisFirewallRules.delete", + "azure.mgmt.redis.operations.FirewallRulesOperations.list": "Microsoft.Cache.RedisFirewallRules.list", + "azure.mgmt.redis.aio.operations.FirewallRulesOperations.list": "Microsoft.Cache.RedisFirewallRules.list", + "azure.mgmt.redis.operations.PatchSchedulesOperations.get": "Microsoft.Cache.RedisPatchSchedules.get", + "azure.mgmt.redis.aio.operations.PatchSchedulesOperations.get": "Microsoft.Cache.RedisPatchSchedules.get", + "azure.mgmt.redis.operations.PatchSchedulesOperations.create_or_update": "Microsoft.Cache.RedisPatchSchedules.createOrUpdate", + "azure.mgmt.redis.aio.operations.PatchSchedulesOperations.create_or_update": "Microsoft.Cache.RedisPatchSchedules.createOrUpdate", + "azure.mgmt.redis.operations.PatchSchedulesOperations.delete": "Microsoft.Cache.RedisPatchSchedules.delete", + "azure.mgmt.redis.aio.operations.PatchSchedulesOperations.delete": "Microsoft.Cache.RedisPatchSchedules.delete", + "azure.mgmt.redis.operations.PatchSchedulesOperations.list_by_redis_resource": "Microsoft.Cache.RedisPatchSchedules.listByRedisResource", + "azure.mgmt.redis.aio.operations.PatchSchedulesOperations.list_by_redis_resource": "Microsoft.Cache.RedisPatchSchedules.listByRedisResource", + "azure.mgmt.redis.operations.AccessPolicyOperations.get": "Microsoft.Cache.RedisCacheAccessPolicies.get", + "azure.mgmt.redis.aio.operations.AccessPolicyOperations.get": "Microsoft.Cache.RedisCacheAccessPolicies.get", + "azure.mgmt.redis.operations.AccessPolicyOperations.begin_create_update": "Microsoft.Cache.RedisCacheAccessPolicies.createUpdate", + "azure.mgmt.redis.aio.operations.AccessPolicyOperations.begin_create_update": "Microsoft.Cache.RedisCacheAccessPolicies.createUpdate", + "azure.mgmt.redis.operations.AccessPolicyOperations.begin_delete": "Microsoft.Cache.RedisCacheAccessPolicies.delete", + "azure.mgmt.redis.aio.operations.AccessPolicyOperations.begin_delete": "Microsoft.Cache.RedisCacheAccessPolicies.delete", + "azure.mgmt.redis.operations.AccessPolicyOperations.list": "Microsoft.Cache.RedisCacheAccessPolicies.list", + "azure.mgmt.redis.aio.operations.AccessPolicyOperations.list": "Microsoft.Cache.RedisCacheAccessPolicies.list", + "azure.mgmt.redis.operations.AccessPolicyAssignmentOperations.get": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.get", + "azure.mgmt.redis.aio.operations.AccessPolicyAssignmentOperations.get": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.get", + "azure.mgmt.redis.operations.AccessPolicyAssignmentOperations.begin_create_update": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.createUpdate", + "azure.mgmt.redis.aio.operations.AccessPolicyAssignmentOperations.begin_create_update": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.createUpdate", + "azure.mgmt.redis.operations.AccessPolicyAssignmentOperations.begin_delete": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.delete", + "azure.mgmt.redis.aio.operations.AccessPolicyAssignmentOperations.begin_delete": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.delete", + "azure.mgmt.redis.operations.AccessPolicyAssignmentOperations.list": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.list", + "azure.mgmt.redis.aio.operations.AccessPolicyAssignmentOperations.list": "Microsoft.Cache.RedisCacheAccessPolicyAssignments.list", + "azure.mgmt.redis.operations.AsyncOperationStatusOperations.get": "Microsoft.Cache.AsyncOperationStatusOperationGroup.get", + "azure.mgmt.redis.aio.operations.AsyncOperationStatusOperations.get": "Microsoft.Cache.AsyncOperationStatusOperationGroup.get" + }, + "CrossLanguageVersion": "6c204dac2fa5" +} \ No newline at end of file diff --git a/sdk/redis/azure-mgmt-redis/azure/__init__.py b/sdk/redis/azure-mgmt-redis/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/redis/azure-mgmt-redis/azure/__init__.py +++ b/sdk/redis/azure-mgmt-redis/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/redis/azure-mgmt-redis/azure/mgmt/__init__.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/__init__.py +++ b/sdk/redis/azure-mgmt-redis/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/redis/azure-mgmt-redis/azure/mgmt/redis/__init__.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/__init__.py index fb8babccaf9a..144d1f8d7681 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/__init__.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/__init__.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. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._redis_management_client import RedisManagementClient # type: ignore +from ._client import RedisManagementClient # type: ignore from ._version import VERSION __version__ = VERSION diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_redis_management_client.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_client.py similarity index 74% rename from sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_redis_management_client.py rename to sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_client.py index c340700fbed3..bc7820f36bac 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_redis_management_client.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_client.py @@ -2,22 +2,23 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING -from typing_extensions import Self +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 RedisManagementClientConfiguration -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer from .operations import ( AccessPolicyAssignmentOperations, AccessPolicyOperations, @@ -31,7 +32,13 @@ RedisOperations, ) +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: + from azure.core import AzureClouds from azure.core.credentials import TokenCredential @@ -40,33 +47,38 @@ class RedisManagementClient: # pylint: disable=too-many-instance-attributes :ivar operations: Operations operations :vartype operations: azure.mgmt.redis.operations.Operations - :ivar redis: RedisOperations operations - :vartype redis: azure.mgmt.redis.operations.RedisOperations - :ivar firewall_rules: FirewallRulesOperations operations - :vartype firewall_rules: azure.mgmt.redis.operations.FirewallRulesOperations - :ivar patch_schedules: PatchSchedulesOperations operations - :vartype patch_schedules: azure.mgmt.redis.operations.PatchSchedulesOperations :ivar linked_server: LinkedServerOperations operations :vartype linked_server: azure.mgmt.redis.operations.LinkedServerOperations :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: azure.mgmt.redis.operations.PrivateEndpointConnectionsOperations + :ivar redis: RedisOperations operations + :vartype redis: azure.mgmt.redis.operations.RedisOperations :ivar private_link_resources: PrivateLinkResourcesOperations operations :vartype private_link_resources: azure.mgmt.redis.operations.PrivateLinkResourcesOperations - :ivar async_operation_status: AsyncOperationStatusOperations operations - :vartype async_operation_status: azure.mgmt.redis.operations.AsyncOperationStatusOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.redis.operations.FirewallRulesOperations + :ivar patch_schedules: PatchSchedulesOperations operations + :vartype patch_schedules: azure.mgmt.redis.operations.PatchSchedulesOperations :ivar access_policy: AccessPolicyOperations operations :vartype access_policy: azure.mgmt.redis.operations.AccessPolicyOperations :ivar access_policy_assignment: AccessPolicyAssignmentOperations operations :vartype access_policy_assignment: azure.mgmt.redis.operations.AccessPolicyAssignmentOperations - :param credential: Credential needed for the client to connect to Azure. Required. + :ivar async_operation_status: AsyncOperationStatusOperations operations + :vartype async_operation_status: azure.mgmt.redis.operations.AsyncOperationStatusOperations + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service host. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2024-11-01". Note that overriding this - default value may result in unsupported behavior. + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2025-08-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -76,12 +88,26 @@ def __init__( self, credential: "TokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = RedisManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + subscription_id=subscription_id, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs ) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -100,38 +126,37 @@ def __init__( policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: ARMPipelineClient = ARMPipelineClient(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.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.redis = RedisOperations(self._client, self._config, self._serialize, self._deserialize) - self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) - self.patch_schedules = PatchSchedulesOperations(self._client, self._config, self._serialize, self._deserialize) self.linked_server = LinkedServerOperations(self._client, self._config, self._serialize, self._deserialize) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( self._client, self._config, self._serialize, self._deserialize ) + self.redis = RedisOperations(self._client, self._config, self._serialize, self._deserialize) self.private_link_resources = PrivateLinkResourcesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.async_operation_status = AsyncOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.patch_schedules = PatchSchedulesOperations(self._client, self._config, self._serialize, self._deserialize) self.access_policy = AccessPolicyOperations(self._client, self._config, self._serialize, self._deserialize) self.access_policy_assignment = AccessPolicyAssignmentOperations( self._client, self._config, self._serialize, self._deserialize ) + self.async_operation_status = AsyncOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **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 @@ -144,7 +169,11 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + 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: diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_configuration.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_configuration.py index d5b392546110..50531215594e 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_configuration.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_configuration.py @@ -2,11 +2,11 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights 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.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy @@ -14,6 +14,7 @@ from ._version import VERSION if TYPE_CHECKING: + from azure.core import AzureClouds from azure.core.credentials import TokenCredential @@ -23,17 +24,31 @@ class RedisManagementClientConfiguration: # pylint: disable=too-many-instance-a Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2024-11-01". Note that overriding this - default value may result in unsupported behavior. + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2025-08-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2024-11-01") + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-08-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -42,6 +57,8 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.credential = credential self.subscription_id = subscription_id + self.base_url = base_url + self.cloud_setting = cloud_setting self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-redis/{}".format(VERSION)) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_patch.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_patch.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_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/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/__init__.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_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/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/model_base.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/model_base.py new file mode 100644 index 000000000000..d725c55906d3 --- /dev/null +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/model_base.py @@ -0,0 +1,1737 @@ +# 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()) + # 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_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, + ): + 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 + + @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, +) -> 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, + ) + + +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/redis/azure-mgmt-redis/azure/mgmt/redis/_serialization.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/serialization.py similarity index 92% rename from sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_serialization.py rename to sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/serialization.py index ce17d1798ce7..a088671e9c51 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_serialization.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_utils/serialization.py @@ -1,28 +1,10 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# 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. # -------------------------------------------------------------------------- # pyright: reportUnnecessaryTypeIgnoreComment=false @@ -39,7 +21,6 @@ import sys import codecs from typing import ( - Dict, Any, cast, Optional, @@ -48,10 +29,7 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, - List, ) try: @@ -65,9 +43,13 @@ 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] @@ -185,73 +167,7 @@ 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. - - :param datetime.datetime dt: The datetime - :returns: The offset - :rtype: datetime.timedelta - """ - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation. - - :param datetime.datetime dt: The datetime - :returns: The timestamp representation - :rtype: str - """ - return "Z" - - def dst(self, dt): - """No daylight saving for UTC. - - :param datetime.datetime dt: The datetime - :returns: The daylight saving time - :rtype: datetime.timedelta - """ - 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) -> None: - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[Dict[str, Any]] = {} + 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__) @@ -397,7 +313,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: 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. @@ -450,25 +366,25 @@ def _infer_class_models(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 - :rtype: ModelType + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) 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 @@ -479,8 +395,8 @@ def from_dict( :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 - :rtype: ModelType + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -500,7 +416,7 @@ 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)) # pylint: disable=protected-access + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access return result @classmethod @@ -563,7 +479,7 @@ def _decode_attribute_map_key(key): return key.replace("\\.", ".") -class Serializer(object): # pylint: disable=too-many-public-methods +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -614,7 +530,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, type] = 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 @@ -626,7 +542,7 @@ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, to :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) @@ -665,7 +581,7 @@ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, to 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: @@ -736,8 +652,8 @@ def body(self, data, data_type, **kwargs): :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 """ @@ -781,8 +697,8 @@ def url(self, name, data, data_type, **kwargs): :param str data_type: The type to be serialized from. :rtype: str :returns: The serialized URL path - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -805,8 +721,8 @@ def query(self, name, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, list - :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 query parameter """ try: @@ -835,8 +751,8 @@ def header(self, name, data, data_type, **kwargs): :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: @@ -855,9 +771,9 @@ def serialize_data(self, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :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 """ @@ -875,7 +791,7 @@ def serialize_data(self, data, data_type, **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) @@ -909,13 +825,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :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 # pylint: disable=eval-used + 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): @@ -1192,7 +1115,7 @@ def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. :return: serialized rfc """ try: @@ -1218,7 +1141,7 @@ def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument :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): @@ -1251,7 +1174,7 @@ def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument :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): @@ -1270,7 +1193,7 @@ def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argumen 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 @@ -1429,7 +1352,7 @@ def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument # 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( # pylint: disable=line-too-long + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( xml_name ) ) @@ -1441,7 +1364,7 @@ def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1472,7 +1395,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, type] = 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 @@ -1482,16 +1405,37 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> 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) @@ -1502,7 +1446,7 @@ def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return :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 """ @@ -1683,17 +1627,21 @@ def _instantiate_model(self, response, attrs, additional_properties=None): subtype = getattr(response, "_subtype_map", {}) try: readonly = [ - k for k, v in response._validation.items() if v.get("readonly") # pylint: disable=protected-access + 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() if v.get("constant") # pylint: disable=protected-access + 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 @@ -1713,7 +1661,7 @@ def deserialize_data(self, data, data_type): # pylint: disable=too-many-return- :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 """ @@ -1795,7 +1743,7 @@ def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return :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 @@ -1841,7 +1789,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :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 @@ -1867,7 +1815,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + 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): @@ -1932,7 +1884,7 @@ def deserialize_bytearray(attr): :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 @@ -1945,7 +1897,7 @@ def deserialize_base64(attr): :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 @@ -1960,7 +1912,7 @@ def deserialize_decimal(attr): :param str attr: response string to be deserialized. :return: Deserialized decimal - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. :rtype: decimal """ if isinstance(attr, ET.Element): @@ -1978,7 +1930,7 @@ def deserialize_long(attr): :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 @@ -1991,7 +1943,7 @@ def deserialize_duration(attr): :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 @@ -2009,7 +1961,7 @@ def deserialize_date(attr): :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 @@ -2025,7 +1977,7 @@ def deserialize_time(attr): :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 @@ -2040,14 +1992,14 @@ def deserialize_rfc(attr): :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) @@ -2063,7 +2015,7 @@ def deserialize_iso(attr): :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 @@ -2101,7 +2053,7 @@ def deserialize_unix(attr): :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 diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_version.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_version.py index 5bd5819bb69a..f5ed26eeaf5d 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_version.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/_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 = "14.5.0" +VERSION = "15.0.0b1" diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/__init__.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/__init__.py index 1f4a5122f162..f170dd5594b6 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/__init__.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/__init__.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. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._redis_management_client import RedisManagementClient # type: ignore +from ._client import RedisManagementClient # type: ignore try: from ._patch import __all__ as _patch_all diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_redis_management_client.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_client.py similarity index 75% rename from sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_redis_management_client.py rename to sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_client.py index 9885931e3fbe..7857fef45d2d 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_redis_management_client.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_client.py @@ -2,21 +2,22 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING -from typing_extensions import Self +import sys +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings from azure.mgmt.core import AsyncARMPipelineClient from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints -from .. import models as _models -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import RedisManagementClientConfiguration from .operations import ( AccessPolicyAssignmentOperations, @@ -31,7 +32,13 @@ RedisOperations, ) +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: + from azure.core import AzureClouds from azure.core.credentials_async import AsyncTokenCredential @@ -40,34 +47,39 @@ class RedisManagementClient: # pylint: disable=too-many-instance-attributes :ivar operations: Operations operations :vartype operations: azure.mgmt.redis.aio.operations.Operations - :ivar redis: RedisOperations operations - :vartype redis: azure.mgmt.redis.aio.operations.RedisOperations - :ivar firewall_rules: FirewallRulesOperations operations - :vartype firewall_rules: azure.mgmt.redis.aio.operations.FirewallRulesOperations - :ivar patch_schedules: PatchSchedulesOperations operations - :vartype patch_schedules: azure.mgmt.redis.aio.operations.PatchSchedulesOperations :ivar linked_server: LinkedServerOperations operations :vartype linked_server: azure.mgmt.redis.aio.operations.LinkedServerOperations :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: azure.mgmt.redis.aio.operations.PrivateEndpointConnectionsOperations + :ivar redis: RedisOperations operations + :vartype redis: azure.mgmt.redis.aio.operations.RedisOperations :ivar private_link_resources: PrivateLinkResourcesOperations operations :vartype private_link_resources: azure.mgmt.redis.aio.operations.PrivateLinkResourcesOperations - :ivar async_operation_status: AsyncOperationStatusOperations operations - :vartype async_operation_status: azure.mgmt.redis.aio.operations.AsyncOperationStatusOperations + :ivar firewall_rules: FirewallRulesOperations operations + :vartype firewall_rules: azure.mgmt.redis.aio.operations.FirewallRulesOperations + :ivar patch_schedules: PatchSchedulesOperations operations + :vartype patch_schedules: azure.mgmt.redis.aio.operations.PatchSchedulesOperations :ivar access_policy: AccessPolicyOperations operations :vartype access_policy: azure.mgmt.redis.aio.operations.AccessPolicyOperations :ivar access_policy_assignment: AccessPolicyAssignmentOperations operations :vartype access_policy_assignment: azure.mgmt.redis.aio.operations.AccessPolicyAssignmentOperations - :param credential: Credential needed for the client to connect to Azure. Required. + :ivar async_operation_status: AsyncOperationStatusOperations operations + :vartype async_operation_status: azure.mgmt.redis.aio.operations.AsyncOperationStatusOperations + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service host. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2024-11-01". Note that overriding this - default value may result in unsupported behavior. + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2025-08-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -77,12 +89,26 @@ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: + _endpoint = "{endpoint}" + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = RedisManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + subscription_id=subscription_id, + base_url=cast(str, base_url), + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs ) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -101,32 +127,33 @@ def __init__( policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) + 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.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.redis = RedisOperations(self._client, self._config, self._serialize, self._deserialize) - self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) - self.patch_schedules = PatchSchedulesOperations(self._client, self._config, self._serialize, self._deserialize) self.linked_server = LinkedServerOperations(self._client, self._config, self._serialize, self._deserialize) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( self._client, self._config, self._serialize, self._deserialize ) + self.redis = RedisOperations(self._client, self._config, self._serialize, self._deserialize) self.private_link_resources = PrivateLinkResourcesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.async_operation_status = AsyncOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.patch_schedules = PatchSchedulesOperations(self._client, self._config, self._serialize, self._deserialize) self.access_policy = AccessPolicyOperations(self._client, self._config, self._serialize, self._deserialize) self.access_policy_assignment = AccessPolicyAssignmentOperations( self._client, self._config, self._serialize, self._deserialize ) + self.async_operation_status = AsyncOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -134,7 +161,7 @@ def _send_request( >>> 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 @@ -147,7 +174,11 @@ def _send_request( """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + 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: diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_configuration.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_configuration.py index ae5732977293..d7ab671919da 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_configuration.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_configuration.py @@ -2,11 +2,11 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights 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.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy @@ -14,6 +14,7 @@ from .._version import VERSION if TYPE_CHECKING: + from azure.core import AzureClouds from azure.core.credentials_async import AsyncTokenCredential @@ -23,17 +24,31 @@ class RedisManagementClientConfiguration: # pylint: disable=too-many-instance-a Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. Required. + :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. + :param subscription_id: The ID of the target subscription. The value must be an UUID. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2024-11-01". Note that overriding this - default value may result in unsupported behavior. + :param base_url: Service host. Default value is "https://management.azure.com". + :type base_url: str + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: The API version to use for this operation. Known values are + "2025-08-01-preview" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ - def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2024-11-01") + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2025-08-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -42,6 +57,8 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.credential = credential self.subscription_id = subscription_id + self.base_url = base_url + self.cloud_setting = cloud_setting self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-redis/{}".format(VERSION)) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_patch.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_patch.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/_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/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/__init__.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/__init__.py index db28d1129b34..723f590f186c 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/__init__.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/__init__.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. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -13,15 +13,15 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import Operations # type: ignore -from ._redis_operations import RedisOperations # type: ignore -from ._firewall_rules_operations import FirewallRulesOperations # type: ignore -from ._patch_schedules_operations import PatchSchedulesOperations # type: ignore -from ._linked_server_operations import LinkedServerOperations # type: ignore -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations # type: ignore -from ._private_link_resources_operations import PrivateLinkResourcesOperations # type: ignore -from ._async_operation_status_operations import AsyncOperationStatusOperations # type: ignore -from ._access_policy_operations import AccessPolicyOperations # type: ignore -from ._access_policy_assignment_operations import AccessPolicyAssignmentOperations # type: ignore +from ._operations import LinkedServerOperations # type: ignore +from ._operations import PrivateEndpointConnectionsOperations # type: ignore +from ._operations import RedisOperations # type: ignore +from ._operations import PrivateLinkResourcesOperations # type: ignore +from ._operations import FirewallRulesOperations # type: ignore +from ._operations import PatchSchedulesOperations # type: ignore +from ._operations import AccessPolicyOperations # type: ignore +from ._operations import AccessPolicyAssignmentOperations # type: ignore +from ._operations import AsyncOperationStatusOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -29,15 +29,15 @@ __all__ = [ "Operations", - "RedisOperations", - "FirewallRulesOperations", - "PatchSchedulesOperations", "LinkedServerOperations", "PrivateEndpointConnectionsOperations", + "RedisOperations", "PrivateLinkResourcesOperations", - "AsyncOperationStatusOperations", + "FirewallRulesOperations", + "PatchSchedulesOperations", "AccessPolicyOperations", "AccessPolicyAssignmentOperations", + "AsyncOperationStatusOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_access_policy_assignment_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_access_policy_assignment_operations.py deleted file mode 100644 index 882147b86556..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_access_policy_assignment_operations.py +++ /dev/null @@ -1,539 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 ...operations._access_policy_assignment_operations import ( - build_create_update_request, - build_delete_request, - build_get_request, - build_list_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class AccessPolicyAssignmentOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`access_policy_assignment` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - async def _create_update_initial( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: Union[_models.RedisCacheAccessPolicyAssignment, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisCacheAccessPolicyAssignment") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: _models.RedisCacheAccessPolicyAssignment, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]: - """Adds the access policy assignment to the specified users. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. - Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment - :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 either RedisCacheAccessPolicyAssignment or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]: - """Adds the access policy assignment to the specified users. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. - Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either RedisCacheAccessPolicyAssignment or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: Union[_models.RedisCacheAccessPolicyAssignment, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]: - """Adds the access policy assignment to the specified users. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. - Is either a RedisCacheAccessPolicyAssignment type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment or IO[bytes] - :return: An instance of AsyncLROPoller that returns either RedisCacheAccessPolicyAssignment or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = 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_update_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - 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): - deserialized = self._deserialize("RedisCacheAccessPolicyAssignment", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisCacheAccessPolicyAssignment].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial( - self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes the access policy assignment from a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any - ) -> _models.RedisCacheAccessPolicyAssignment: - """Gets the list of assignments for an access policy of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :return: RedisCacheAccessPolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisCacheAccessPolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncIterable["_models.RedisCacheAccessPolicyAssignment"]: - """Gets the list of access policy assignments associated with this redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisCacheAccessPolicyAssignment or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicyAssignmentList] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RedisCacheAccessPolicyAssignmentList", 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) - - _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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_access_policy_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_access_policy_operations.py deleted file mode 100644 index bb81c3551f04..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_access_policy_operations.py +++ /dev/null @@ -1,539 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 ...operations._access_policy_operations import ( - build_create_update_request, - build_delete_request, - build_get_request, - build_list_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class AccessPolicyOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`access_policy` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - async def _create_update_initial( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: Union[_models.RedisCacheAccessPolicy, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisCacheAccessPolicy") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: _models.RedisCacheAccessPolicy, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisCacheAccessPolicy]: - """Adds an access policy to the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy - :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 either RedisCacheAccessPolicy or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisCacheAccessPolicy]: - """Adds an access policy to the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either RedisCacheAccessPolicy or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: Union[_models.RedisCacheAccessPolicy, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisCacheAccessPolicy]: - """Adds an access policy to the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :param parameters: Parameters supplied to the Create Update Access Policy operation. Is either - a RedisCacheAccessPolicy type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy or IO[bytes] - :return: An instance of AsyncLROPoller that returns either RedisCacheAccessPolicy or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisCacheAccessPolicy] = 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_update_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - 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): - deserialized = self._deserialize("RedisCacheAccessPolicy", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisCacheAccessPolicy].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.RedisCacheAccessPolicy]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial( - self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes the access policy from a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any - ) -> _models.RedisCacheAccessPolicy: - """Gets the detailed information about an access policy of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :return: RedisCacheAccessPolicy or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicy - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicy] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisCacheAccessPolicy", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncIterable["_models.RedisCacheAccessPolicy"]: - """Gets the list of access policies associated with this redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisCacheAccessPolicy or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicyList] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RedisCacheAccessPolicyList", 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) - - _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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_async_operation_status_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_async_operation_status_operations.py deleted file mode 100644 index 7b8eb4163ad8..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_async_operation_status_operations.py +++ /dev/null @@ -1,108 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, 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 ...operations._async_operation_status_operations import build_get_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class AsyncOperationStatusOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`async_operation_status` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def get(self, location: str, operation_id: str, **kwargs: Any) -> _models.OperationStatus: - """For checking the ongoing status of an operation. - - :param location: The location at which operation was triggered. Required. - :type location: str - :param operation_id: The ID of asynchronous operation. Required. - :type operation_id: str - :return: OperationStatus or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.OperationStatus - :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", self._config.api_version)) - cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) - - _request = build_get_request( - location=location, - operation_id=operation_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("OperationStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_firewall_rules_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_firewall_rules_operations.py deleted file mode 100644 index f8db8592849e..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_firewall_rules_operations.py +++ /dev/null @@ -1,405 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.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 ... import models as _models -from ...operations._firewall_rules_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class FirewallRulesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`firewall_rules` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncIterable["_models.RedisFirewallRule"]: - """Gets all firewall rules in the specified redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisFirewallRule or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisFirewallRule] - :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", self._config.api_version)) - cls: ClsType[_models.RedisFirewallRuleListResult] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RedisFirewallRuleListResult", 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) - - _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 = 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) - - @overload - async def create_or_update( - self, - resource_group_name: str, - cache_name: str, - rule_name: str, - parameters: _models.RedisFirewallRule, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisFirewallRule: - """Create or update a redis cache firewall rule. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :param parameters: Parameters supplied to the create or update redis firewall rule operation. - Required. - :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - cache_name: str, - rule_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisFirewallRule: - """Create or update a redis cache firewall rule. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :param parameters: Parameters supplied to the create or update redis firewall rule operation. - Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - resource_group_name: str, - cache_name: str, - rule_name: str, - parameters: Union[_models.RedisFirewallRule, IO[bytes]], - **kwargs: Any - ) -> _models.RedisFirewallRule: - """Create or update a redis cache firewall rule. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :param parameters: Parameters supplied to the create or update redis firewall rule operation. - Is either a RedisFirewallRule type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule or IO[bytes] - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisFirewallRule] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisFirewallRule") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - rule_name=rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisFirewallRule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any - ) -> _models.RedisFirewallRule: - """Gets a single firewall rule in a specified redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :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", self._config.api_version)) - cls: ClsType[_models.RedisFirewallRule] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - rule_name=rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisFirewallRule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete(self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any) -> None: - """Deletes a single firewall rule in a specified redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :return: None or the result of cls(response) - :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", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - rule_name=rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_linked_server_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_linked_server_operations.py deleted file mode 100644 index 979af08e92ec..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_linked_server_operations.py +++ /dev/null @@ -1,539 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 ...operations._linked_server_operations import ( - build_create_request, - build_delete_request, - build_get_request, - build_list_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class LinkedServerOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`linked_server` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - async def _create_initial( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: Union[_models.RedisLinkedServerCreateParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisLinkedServerCreateParameters") - - _request = build_create_request( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: _models.RedisLinkedServerCreateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisLinkedServerWithProperties]: - """Adds a linked server to the Redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :param parameters: Parameters supplied to the Create Linked server operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters - :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 either RedisLinkedServerWithProperties or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisLinkedServerWithProperties]: - """Adds a linked server to the Redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :param parameters: Parameters supplied to the Create Linked server operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either RedisLinkedServerWithProperties or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: Union[_models.RedisLinkedServerCreateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisLinkedServerWithProperties]: - """Adds a linked server to the Redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :param parameters: Parameters supplied to the Create Linked server operation. Is either a - RedisLinkedServerCreateParameters type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either RedisLinkedServerWithProperties or - the result of cls(response) - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisLinkedServerWithProperties] = 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_initial( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - 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): - deserialized = self._deserialize("RedisLinkedServerWithProperties", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisLinkedServerWithProperties].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.RedisLinkedServerWithProperties]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial( - self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes the linked server from a redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any - ) -> _models.RedisLinkedServerWithProperties: - """Gets the detailed information about a linked server of a redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server. Required. - :type linked_server_name: str - :return: RedisLinkedServerWithProperties or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisLinkedServerWithProperties - :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", self._config.api_version)) - cls: ClsType[_models.RedisLinkedServerWithProperties] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisLinkedServerWithProperties", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, resource_group_name: str, name: str, **kwargs: Any - ) -> AsyncIterable["_models.RedisLinkedServerWithProperties"]: - """Gets the list of linked servers associated with this redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :return: An iterator like instance of either RedisLinkedServerWithProperties or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :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", self._config.api_version)) - cls: ClsType[_models.RedisLinkedServerWithPropertiesList] = 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_list_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RedisLinkedServerWithPropertiesList", 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) - - _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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_operations.py index 1e2c3ab785da..258224f543cf 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_operations.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_operations.py @@ -1,14 +1,18 @@ +# 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. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -16,23 +20,71 @@ 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 ...operations._operations import build_list_request +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_access_policy_assignment_create_update_request, + build_access_policy_assignment_delete_request, + build_access_policy_assignment_get_request, + build_access_policy_assignment_list_request, + build_access_policy_create_update_request, + build_access_policy_delete_request, + build_access_policy_get_request, + build_access_policy_list_request, + build_async_operation_status_get_request, + build_firewall_rules_create_or_update_request, + build_firewall_rules_delete_request, + build_firewall_rules_get_request, + build_firewall_rules_list_request, + build_linked_server_create_request, + build_linked_server_delete_request, + build_linked_server_get_request, + build_linked_server_list_request, + build_operations_list_request, + build_patch_schedules_create_or_update_request, + build_patch_schedules_delete_request, + build_patch_schedules_get_request, + build_patch_schedules_list_by_redis_resource_request, + build_private_endpoint_connections_delete_request, + build_private_endpoint_connections_get_request, + build_private_endpoint_connections_list_request, + build_private_endpoint_connections_put_request, + build_private_link_resources_list_by_redis_cache_request, + build_redis_check_name_availability_request, + build_redis_create_request, + build_redis_delete_request, + build_redis_export_data_request, + build_redis_flush_cache_request, + build_redis_force_reboot_request, + build_redis_get_request, + build_redis_import_data_request, + build_redis_list_by_resource_group_request, + build_redis_list_by_subscription_request, + build_redis_list_keys_request, + build_redis_list_upgrade_notifications_request, + build_redis_regenerate_key_request, + build_redis_update_request, +) +from .._configuration import RedisManagementClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +List = list class Operations: @@ -45,28 +97,596 @@ class Operations: :attr:`operations` attribute. """ - models = _models - def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: - """Lists all of the available REST API operations of the Microsoft.Cache provider. + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: + """List the operations for the provider. - :return: An iterator like instance of either Operation or the result of cls(response) + :return: An iterator like instance of Operation :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Operation], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class LinkedServerOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`linked_server` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any + ) -> _models.RedisLinkedServerWithProperties: + """Gets the detailed information about a linked server of a redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :return: RedisLinkedServerWithProperties. The RedisLinkedServerWithProperties is compatible + with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisLinkedServerWithProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisLinkedServerWithProperties] = kwargs.pop("cls", None) + + _request = build_linked_server_get_request( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisLinkedServerWithProperties, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_initial( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: Union[_models.RedisLinkedServerCreateParameters, 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 = kwargs.pop("params", {}) or {} + + 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_linked_server_create_request( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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")) + + 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( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: _models.RedisLinkedServerCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters + :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 RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: Union[_models.RedisLinkedServerCreateParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Is one of the + following types: RedisLinkedServerCreateParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters or JSON or + IO[bytes] + :return: An instance of AsyncLROPoller that returns RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisLinkedServerWithProperties] = 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_initial( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + parameters=parameters, + 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.RedisLinkedServerWithProperties, 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.RedisLinkedServerWithProperties].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.RedisLinkedServerWithProperties]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_linked_server_delete_request( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the linked server from a redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.RedisLinkedServerWithProperties"]: + """Gets the list of linked servers associated with this redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :return: An iterator like instance of RedisLinkedServerWithProperties + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.RedisLinkedServerWithProperties]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -79,12 +699,20 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - _request = build_list_request( - api_version=api_version, + _request = build_linked_server_list_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, headers=_headers, params=_params, ) - _request.url = self._client.format_url(_request.url) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -97,18 +725,29 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisLinkedServerWithProperties], + deserialized.get("value", []), + ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): _request = prepare_request(next_link) @@ -121,9 +760,4857 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) + + +class PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`private_endpoint_connections` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Gets the specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: PrivateEndpointConnection. The PrivateEndpointConnection is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + _request = build_private_endpoint_connections_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PrivateEndpointConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _put_initial( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: Union[_models.PrivateEndpointConnection, 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 = kwargs.pop("params", {}) or {} + + 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(properties, (IOBase, bytes)): + _content = properties + else: + _content = json.dumps(properties, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_private_endpoint_connections_put_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Required. + :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection + :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 PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Required. + :type properties: 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 PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Required. + :type properties: 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 PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: Union[_models.PrivateEndpointConnection, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Is one of the following types: + PrivateEndpointConnection, JSON, IO[bytes] Required. + :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = 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._put_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + properties=properties, + 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.PrivateEndpointConnection, 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.PrivateEndpointConnection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + async def delete( + self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> None: + """Deletes the specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_private_endpoint_connections_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.PrivateEndpointConnection"]: + """List all the private endpoint connections associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of PrivateEndpointConnection + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PrivateEndpointConnection]] = 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_private_endpoint_connections_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.PrivateEndpointConnection], + 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 RedisOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`redis` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisResource: + """Gets a Redis cache (resource description). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :return: RedisResource. The RedisResource is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisResource] = kwargs.pop("cls", None) + + _request = build_redis_get_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisCreateParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_create_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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")) + + 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( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters + :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 RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisCreateParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Is one of the following + types: RedisCreateParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisResource] = 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_initial( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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.RedisResource, 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.RedisResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.RedisResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _update_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisUpdateParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_update_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_update( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters + :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 RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisUpdateParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Is one of the following + types: RedisUpdateParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns RedisResource. The RedisResource is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisResource] = 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( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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.RedisResource, 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.RedisResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.RedisResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial(self, resource_group_name: str, name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_redis_delete_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace_async + async def begin_delete(self, resource_group_name: str, name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Deletes a Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + name=name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.RedisResource"]: + """Lists all Redis caches in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of RedisResource + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisResource]] = 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_redis_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> AsyncItemPaged["_models.RedisResource"]: + """Gets all Redis caches in the specified subscription. + + :return: An iterator like instance of RedisResource + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisResource]] = 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_redis_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_upgrade_notifications( + self, resource_group_name: str, name: str, *, history: float, **kwargs: Any + ) -> AsyncItemPaged["_models.UpgradeNotification"]: + """[Deprecated] Gets any upgrade notifications for a Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :keyword history: how many minutes in past to look for upgrade notifications. Required. + :paramtype history: float + :return: An iterator like instance of UpgradeNotification + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.UpgradeNotification] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.UpgradeNotification]] = 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_redis_list_upgrade_notifications_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + history=history, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.UpgradeNotification], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def list_keys(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisAccessKeys: + """Retrieve a Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :return: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisAccessKeys] = kwargs.pop("cls", None) + + _request = build_redis_list_keys_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisAccessKeys, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisRegenerateKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. Required. + :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. 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: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. 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: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisRegenerateKeyParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. Is one of the following types: + RedisRegenerateKeyParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters or JSON or IO[bytes] + :return: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisAccessKeys] = 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_redis_regenerate_key_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisAccessKeys, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisRebootParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. Required. + :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. 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: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. 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: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisRebootParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. Is one of the following types: + RedisRebootParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters or JSON or IO[bytes] + :return: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisForceRebootResponse] = 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_redis_force_reboot_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisForceRebootResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _import_data_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ImportRDBParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_import_data_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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_import_data( + self, + resource_group_name: str, + name: str, + parameters: _models.ImportRDBParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Required. + :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters + :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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_import_data( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_import_data( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_import_data( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ImportRDBParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Is one of the following types: + ImportRDBParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = 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._import_data_initial( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _export_data_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ExportRDBParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_export_data_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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_export_data( + self, + resource_group_name: str, + name: str, + parameters: _models.ExportRDBParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Required. + :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters + :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 None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_export_data( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_export_data( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_export_data( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ExportRDBParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Is one of the following types: + ExportRDBParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = 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._export_data_initial( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + async def _flush_cache_initial( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_redis_flush_cache_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_flush_cache( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatusResult]: + """Deletes all of the keys in a cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An instance of AsyncLROPoller that returns OperationStatusResult. The + OperationStatusResult is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.OperationStatusResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationStatusResult] = 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._flush_cache_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = _deserialize(_models.OperationStatusResult, 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.OperationStatusResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.OperationStatusResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + async def check_name_availability( + self, + parameters: _models.CheckNameAvailabilityParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. Required. + :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. 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: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. 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: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, parameters: Union[_models.CheckNameAvailabilityParameters, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. Is one of the following types: + CheckNameAvailabilityParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters or JSON or IO[bytes] + :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 = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = 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_redis_check_name_availability_request( + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _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) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`private_link_resources` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_redis_cache( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.PrivateLinkResource"]: + """Gets the private link resources that need to be created for a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of PrivateLinkResource + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PrivateLinkResource]] = 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_private_link_resources_list_by_redis_cache_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.PrivateLinkResource], + 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 FirewallRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`firewall_rules` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any + ) -> _models.RedisFirewallRule: + """Gets a single firewall rule in a specified redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisFirewallRule] = kwargs.pop("cls", None) + + _request = build_firewall_rules_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + rule_name=rule_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisFirewallRule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: _models.RedisFirewallRule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Required. + :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: Union[_models.RedisFirewallRule, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Is one of the following types: RedisFirewallRule, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule or JSON or IO[bytes] + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisFirewallRule] = 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_firewall_rules_create_or_update_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + rule_name=rule_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisFirewallRule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any) -> None: + """Deletes a single firewall rule in a specified redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_firewall_rules_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + rule_name=rule_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.RedisFirewallRule"]: + """Gets all firewall rules in the specified redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisFirewallRule + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisFirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisFirewallRule]] = 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_firewall_rules_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisFirewallRule], + 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 PatchSchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`patch_schedules` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Gets the patching schedule of a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :return: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisPatchSchedule] = kwargs.pop("cls", None) + + _request = build_patch_schedules_get_request( + resource_group_name=resource_group_name, + name=name, + default=default, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisPatchSchedule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: _models.RedisPatchSchedule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. Required. + :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. 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: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. 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: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: Union[_models.RedisPatchSchedule, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. Is one of the + following types: RedisPatchSchedule, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule or JSON or IO[bytes] + :return: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisPatchSchedule] = 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_patch_schedules_create_or_update_request( + resource_group_name=resource_group_name, + name=name, + default=default, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisPatchSchedule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete( + self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any + ) -> None: + """Deletes the patching schedule of a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_patch_schedules_delete_request( + resource_group_name=resource_group_name, + name=name, + default=default, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_by_redis_resource( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.RedisPatchSchedule"]: + """Gets all patch schedules in the specified redis cache (there is only one). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisPatchSchedule + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisPatchSchedule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisPatchSchedule]] = 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_patch_schedules_list_by_redis_resource_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisPatchSchedule], + 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 AccessPolicyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`access_policy` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any + ) -> _models.RedisCacheAccessPolicy: + """Gets the detailed information about an access policy of a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :return: RedisCacheAccessPolicy. The RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisCacheAccessPolicy] = kwargs.pop("cls", None) + + _request = build_access_policy_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisCacheAccessPolicy, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_initial( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: Union[_models.RedisCacheAccessPolicy, 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 = kwargs.pop("params", {}) or {} + + 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_access_policy_create_update_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: _models.RedisCacheAccessPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy + :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 RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: Union[_models.RedisCacheAccessPolicy, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Is one of + the following types: RedisCacheAccessPolicy, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy or JSON or IO[bytes] + :return: An instance of AsyncLROPoller that returns RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisCacheAccessPolicy] = 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_update_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + parameters=parameters, + 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.RedisCacheAccessPolicy, 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.RedisCacheAccessPolicy].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.RedisCacheAccessPolicy]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_access_policy_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the access policy from a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.RedisCacheAccessPolicy"]: + """Gets the list of access policies associated with this redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisCacheAccessPolicy + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisCacheAccessPolicy]] = 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_access_policy_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisCacheAccessPolicy], + 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 AccessPolicyAssignmentOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`access_policy_assignment` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any + ) -> _models.RedisCacheAccessPolicyAssignment: + """Gets the list of assignments for an access policy of a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :return: RedisCacheAccessPolicyAssignment. The RedisCacheAccessPolicyAssignment is compatible + with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = kwargs.pop("cls", None) + + _request = build_access_policy_assignment_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisCacheAccessPolicyAssignment, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _create_update_initial( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: Union[_models.RedisCacheAccessPolicyAssignment, 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 = kwargs.pop("params", {}) or {} + + 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_access_policy_assignment_create_update_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: _models.RedisCacheAccessPolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment + :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 RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: Union[_models.RedisCacheAccessPolicyAssignment, JSON, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Is one of the following types: RedisCacheAccessPolicyAssignment, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment or JSON or + IO[bytes] + :return: An instance of AsyncLROPoller that returns RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = 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_update_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + parameters=parameters, + 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.RedisCacheAccessPolicyAssignment, 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.RedisCacheAccessPolicyAssignment].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.RedisCacheAccessPolicyAssignment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_access_policy_assignment_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes the access policy assignment from a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.RedisCacheAccessPolicyAssignment"]: + """Gets the list of access policy assignments associated with this redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisCacheAccessPolicyAssignment + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisCacheAccessPolicyAssignment]] = 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_access_policy_assignment_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisCacheAccessPolicyAssignment], + 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 AsyncOperationStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s + :attr:`async_operation_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: RedisManagementClientConfiguration = 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, location: str, operation_id: str, **kwargs: Any) -> _models.OperationStatus: + """For checking the ongoing status of an operation. + + :param location: The location at which operation was triggered. Required. + :type location: str + :param operation_id: The ID of asynchronous operation. Required. + :type operation_id: str + :return: OperationStatus. The OperationStatus is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.OperationStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) + + _request = build_async_operation_status_get_request( + location=location, + operation_id=operation_id, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.OperationStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_patch.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_patch.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/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/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_patch_schedules_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_patch_schedules_operations.py deleted file mode 100644 index 95dbe5053f28..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_patch_schedules_operations.py +++ /dev/null @@ -1,410 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.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 ... import models as _models -from ...operations._patch_schedules_operations import ( - build_create_or_update_request, - build_delete_request, - build_get_request, - build_list_by_redis_resource_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PatchSchedulesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`patch_schedules` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_redis_resource( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncIterable["_models.RedisPatchSchedule"]: - """Gets all patch schedules in the specified redis cache (there is only one). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisPatchSchedule] - :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", self._config.api_version)) - cls: ClsType[_models.RedisPatchScheduleListResult] = 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_list_by_redis_resource_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RedisPatchScheduleListResult", 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) - - _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 = 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) - - @overload - async def create_or_update( - self, - resource_group_name: str, - name: str, - default: Union[str, _models.DefaultName], - parameters: _models.RedisPatchSchedule, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Create or replace the patching schedule for Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :param parameters: Parameters to set the patching schedule for Redis cache. Required. - :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - name: str, - default: Union[str, _models.DefaultName], - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Create or replace the patching schedule for Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :param parameters: Parameters to set the patching schedule for Redis cache. 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: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - resource_group_name: str, - name: str, - default: Union[str, _models.DefaultName], - parameters: Union[_models.RedisPatchSchedule, IO[bytes]], - **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Create or replace the patching schedule for Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :param parameters: Parameters to set the patching schedule for Redis cache. Is either a - RedisPatchSchedule type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule or IO[bytes] - :return: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisPatchSchedule] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisPatchSchedule") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - name=name, - default=default, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisPatchSchedule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete( - self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any - ) -> None: - """Deletes the patching schedule of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :return: None or the result of cls(response) - :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", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - name=name, - default=default, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Gets the patching schedule of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :return: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :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", self._config.api_version)) - cls: ClsType[_models.RedisPatchSchedule] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - name=name, - default=default, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisPatchSchedule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_private_endpoint_connections_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_private_endpoint_connections_operations.py deleted file mode 100644 index ccadc7556d02..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_private_endpoint_connections_operations.py +++ /dev/null @@ -1,480 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 ...operations._private_endpoint_connections_operations import ( - build_delete_request, - build_get_request, - build_list_request, - build_put_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PrivateEndpointConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`private_endpoint_connections` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncIterable["_models.PrivateEndpointConnection"]: - """List all the private endpoint connections associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either PrivateEndpointConnection or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.PrivateEndpointConnection] - :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", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnectionListResult] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return 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 = 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) - - @distributed_trace_async - async def get( - self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Gets the specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.PrivateEndpointConnection - :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", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _put_initial( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(properties, (IOBase, bytes)): - _content = properties - else: - _json = self._serialize.body(properties, "PrivateEndpointConnection") - - _request = build_put_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_put( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: _models.PrivateEndpointConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: - """Update the state of specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :param properties: The private endpoint connection properties. Required. - :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection - :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 either PrivateEndpointConnection or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_put( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: - """Update the state of specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :param properties: The private endpoint connection properties. Required. - :type properties: 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 either PrivateEndpointConnection or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_put( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: - """Update the state of specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :param properties: The private endpoint connection properties. Is either a - PrivateEndpointConnection type or a IO[bytes] type. Required. - :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection or IO[bytes] - :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the - result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PrivateEndpointConnection] = 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._put_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - properties=properties, - 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): - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.PrivateEndpointConnection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.PrivateEndpointConnection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace_async - async def delete( - self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - """Deletes the specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :return: None or the result of cls(response) - :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", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_private_link_resources_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_private_link_resources_operations.py deleted file mode 100644 index b148bbb46540..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_private_link_resources_operations.py +++ /dev/null @@ -1,139 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar -import urllib.parse - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, 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 ...operations._private_link_resources_operations import build_list_by_redis_cache_request - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class PrivateLinkResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`private_link_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_redis_cache( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncIterable["_models.PrivateLinkResource"]: - """Gets the private link resources that need to be created for a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.PrivateLinkResource] - :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", self._config.api_version)) - cls: ClsType[_models.PrivateLinkResourceListResult] = 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_list_by_redis_cache_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return 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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_redis_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_redis_operations.py deleted file mode 100644 index 0a464aade924..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/aio/operations/_redis_operations.py +++ /dev/null @@ -1,1786 +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. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 ...operations._redis_operations import ( - build_check_name_availability_request, - build_create_request, - build_delete_request, - build_export_data_request, - build_flush_cache_request, - build_force_reboot_request, - build_get_request, - build_import_data_request, - build_list_by_resource_group_request, - build_list_by_subscription_request, - build_list_keys_request, - build_list_upgrade_notifications_request, - build_regenerate_key_request, - build_update_request, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class RedisOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.aio.RedisManagementClient`'s - :attr:`redis` 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 check_name_availability( - self, - parameters: _models.CheckNameAvailabilityParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Checks that the redis cache name is valid and is not already in use. - - :param parameters: Parameters supplied to the CheckNameAvailability Redis operation. The only - supported resource type is 'Microsoft.Cache/redis'. Required. - :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def check_name_availability( - self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Checks that the redis cache name is valid and is not already in use. - - :param parameters: Parameters supplied to the CheckNameAvailability Redis operation. The only - supported resource type is 'Microsoft.Cache/redis'. 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: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def check_name_availability( - self, parameters: Union[_models.CheckNameAvailabilityParameters, IO[bytes]], **kwargs: Any - ) -> None: - """Checks that the redis cache name is valid and is not already in use. - - :param parameters: Parameters supplied to the CheckNameAvailability Redis operation. The only - supported resource type is 'Microsoft.Cache/redis'. Is either a CheckNameAvailabilityParameters - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters or IO[bytes] - :return: None or the result of cls(response) - :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 = 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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") - - _request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def list_upgrade_notifications( - self, resource_group_name: str, name: str, history: float, **kwargs: Any - ) -> AsyncIterable["_models.UpgradeNotification"]: - """Gets any upgrade notifications for a Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param history: how many minutes in past to look for upgrade notifications. Required. - :type history: float - :return: An iterator like instance of either UpgradeNotification or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.UpgradeNotification] - :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", self._config.api_version)) - cls: ClsType[_models.NotificationListResponse] = 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_list_upgrade_notifications_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - history=history, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("NotificationListResponse", 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) - - _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 = 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) - - async def _create_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisCreateParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisCreateParameters") - - _request = build_create_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_create( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisCreateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisResource]: - """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Create Redis operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters - :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 either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_create( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisResource]: - """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Create Redis operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_create( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisCreateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisResource]: - """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Create Redis operation. Is either a - RedisCreateParameters type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisResource] = 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_initial( - resource_group_name=resource_group_name, - name=name, - 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): - deserialized = self._deserialize("RedisResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.RedisResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _update_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisUpdateParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisUpdateParameters") - - _request = build_update_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_update( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisResource]: - """Update an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Update Redis operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters - :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 either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_update( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisResource]: - """Update an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Update Redis operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_update( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[_models.RedisResource]: - """Update an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Update Redis operation. Is either a - RedisUpdateParameters type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisResource] = 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( - resource_group_name=resource_group_name, - name=name, - 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): - deserialized = self._deserialize("RedisResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.RedisResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _delete_initial(self, resource_group_name: str, name: str, **kwargs: Any) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_delete(self, resource_group_name: str, name: str, **kwargs: Any) -> AsyncLROPoller[None]: - """Deletes a Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - name=name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace_async - async def get(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisResource: - """Gets a Redis cache (resource description). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :return: RedisResource or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisResource - :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", self._config.api_version)) - cls: ClsType[_models.RedisResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.RedisResource"]: - """Lists all Redis caches in a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either RedisResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - cls: ClsType[_models.RedisListResult] = 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_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RedisListResult", 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) - - _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 = 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) - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.RedisResource"]: - """Gets all Redis caches in the specified subscription. - - :return: An iterator like instance of either RedisResource or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - cls: ClsType[_models.RedisListResult] = 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_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RedisListResult", 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) - - _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 = 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) - - @distributed_trace_async - async def list_keys(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisAccessKeys: - """Retrieve a Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :return: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :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", self._config.api_version)) - cls: ClsType[_models.RedisAccessKeys] = kwargs.pop("cls", None) - - _request = build_list_keys_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisAccessKeys", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def regenerate_key( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisRegenerateKeyParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisAccessKeys: - """Regenerate Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which key to regenerate. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def regenerate_key( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisAccessKeys: - """Regenerate Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which key to regenerate. 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: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def regenerate_key( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisRegenerateKeyParameters, IO[bytes]], - **kwargs: Any - ) -> _models.RedisAccessKeys: - """Regenerate Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which key to regenerate. Is either a RedisRegenerateKeyParameters - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters or IO[bytes] - :return: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisAccessKeys] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisRegenerateKeyParameters") - - _request = build_regenerate_key_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisAccessKeys", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def force_reboot( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisRebootParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisForceRebootResponse: - """Reboot specified Redis node(s). This operation requires write permission to the cache resource. - There can be potential data loss. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which Redis node(s) to reboot. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisForceRebootResponse or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def force_reboot( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisForceRebootResponse: - """Reboot specified Redis node(s). This operation requires write permission to the cache resource. - There can be potential data loss. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which Redis node(s) to reboot. 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: RedisForceRebootResponse or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def force_reboot( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisRebootParameters, IO[bytes]], - **kwargs: Any - ) -> _models.RedisForceRebootResponse: - """Reboot specified Redis node(s). This operation requires write permission to the cache resource. - There can be potential data loss. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which Redis node(s) to reboot. Is either a RedisRebootParameters - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters or IO[bytes] - :return: RedisForceRebootResponse or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisForceRebootResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisRebootParameters") - - _request = build_force_reboot_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisForceRebootResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _import_data_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ImportRDBParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ImportRDBParameters") - - _request = build_import_data_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_import_data( - self, - resource_group_name: str, - name: str, - parameters: _models.ImportRDBParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Import data into Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis import operation. Required. - :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters - :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 either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_import_data( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Import data into Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis import operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_import_data( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ImportRDBParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Import data into Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis import operation. Is either a ImportRDBParameters type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = 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._import_data_initial( - resource_group_name=resource_group_name, - name=name, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _export_data_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ExportRDBParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ExportRDBParameters") - - _request = build_export_data_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_export_data( - self, - resource_group_name: str, - name: str, - parameters: _models.ExportRDBParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Export data from the redis cache to blobs in a container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis export operation. Required. - :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters - :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 either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_export_data( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Export data from the redis cache to blobs in a container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis export operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_export_data( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ExportRDBParameters, IO[bytes]], - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Export data from the redis cache to blobs in a container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis export operation. Is either a ExportRDBParameters type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters or IO[bytes] - :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[None] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = 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._export_data_initial( - resource_group_name=resource_group_name, - name=name, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - async def _flush_cache_initial( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_flush_cache_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def begin_flush_cache( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.OperationStatusResult]: - """Deletes all of the keys in a cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An instance of AsyncLROPoller that returns either OperationStatusResult or the result - of cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.redis.models.OperationStatusResult] - :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", self._config.api_version)) - cls: ClsType[_models.OperationStatusResult] = 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._flush_cache_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - api_version=api_version, - 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["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - - deserialized = self._deserialize("OperationStatusResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - 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[_models.OperationStatusResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.OperationStatusResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/__init__.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/__init__.py index afdb5e585b3a..c175fb9bc8dd 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/__init__.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/__init__.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. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -13,7 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import -from ._models_py3 import ( # type: ignore +from ._models import ( # type: ignore CheckNameAvailabilityParameters, ErrorAdditionalInfo, ErrorDetail, @@ -21,31 +21,28 @@ ExportRDBParameters, ImportRDBParameters, ManagedServiceIdentity, - NotificationListResponse, Operation, OperationDisplay, - OperationListResult, OperationStatus, OperationStatusResult, PrivateEndpoint, PrivateEndpointConnection, - PrivateEndpointConnectionListResult, + PrivateEndpointConnectionProperties, PrivateLinkResource, - PrivateLinkResourceListResult, + PrivateLinkResourceProperties, PrivateLinkServiceConnectionState, ProxyResource, RedisAccessKeys, RedisCacheAccessPolicy, RedisCacheAccessPolicyAssignment, - RedisCacheAccessPolicyAssignmentList, - RedisCacheAccessPolicyList, + RedisCacheAccessPolicyAssignmentProperties, + RedisCacheAccessPolicyProperties, RedisCommonProperties, RedisCommonPropertiesRedisConfiguration, RedisCreateParameters, RedisCreateProperties, RedisFirewallRule, - RedisFirewallRuleCreateParameters, - RedisFirewallRuleListResult, + RedisFirewallRuleProperties, RedisForceRebootResponse, RedisInstanceDetails, RedisLinkedServer, @@ -53,10 +50,7 @@ RedisLinkedServerCreateProperties, RedisLinkedServerProperties, RedisLinkedServerWithProperties, - RedisLinkedServerWithPropertiesList, - RedisListResult, RedisPatchSchedule, - RedisPatchScheduleListResult, RedisProperties, RedisRebootParameters, RedisRegenerateKeyParameters, @@ -64,17 +58,20 @@ RedisUpdateParameters, RedisUpdateProperties, Resource, + ScheduleEntries, ScheduleEntry, Sku, + SystemData, TrackedResource, UpgradeNotification, UserAssignedIdentity, ) -from ._redis_management_client_enums import ( # type: ignore +from ._enums import ( # type: ignore AccessPolicyAssignmentProvisioningState, AccessPolicyProvisioningState, AccessPolicyType, + CreatedByType, DayOfWeek, DefaultName, ManagedServiceIdentityType, @@ -103,31 +100,28 @@ "ExportRDBParameters", "ImportRDBParameters", "ManagedServiceIdentity", - "NotificationListResponse", "Operation", "OperationDisplay", - "OperationListResult", "OperationStatus", "OperationStatusResult", "PrivateEndpoint", "PrivateEndpointConnection", - "PrivateEndpointConnectionListResult", + "PrivateEndpointConnectionProperties", "PrivateLinkResource", - "PrivateLinkResourceListResult", + "PrivateLinkResourceProperties", "PrivateLinkServiceConnectionState", "ProxyResource", "RedisAccessKeys", "RedisCacheAccessPolicy", "RedisCacheAccessPolicyAssignment", - "RedisCacheAccessPolicyAssignmentList", - "RedisCacheAccessPolicyList", + "RedisCacheAccessPolicyAssignmentProperties", + "RedisCacheAccessPolicyProperties", "RedisCommonProperties", "RedisCommonPropertiesRedisConfiguration", "RedisCreateParameters", "RedisCreateProperties", "RedisFirewallRule", - "RedisFirewallRuleCreateParameters", - "RedisFirewallRuleListResult", + "RedisFirewallRuleProperties", "RedisForceRebootResponse", "RedisInstanceDetails", "RedisLinkedServer", @@ -135,10 +129,7 @@ "RedisLinkedServerCreateProperties", "RedisLinkedServerProperties", "RedisLinkedServerWithProperties", - "RedisLinkedServerWithPropertiesList", - "RedisListResult", "RedisPatchSchedule", - "RedisPatchScheduleListResult", "RedisProperties", "RedisRebootParameters", "RedisRegenerateKeyParameters", @@ -146,14 +137,17 @@ "RedisUpdateParameters", "RedisUpdateProperties", "Resource", + "ScheduleEntries", "ScheduleEntry", "Sku", + "SystemData", "TrackedResource", "UpgradeNotification", "UserAssignedIdentity", "AccessPolicyAssignmentProvisioningState", "AccessPolicyProvisioningState", "AccessPolicyType", + "CreatedByType", "DayOfWeek", "DefaultName", "ManagedServiceIdentityType", diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_enums.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_enums.py new file mode 100644 index 000000000000..c2f602df20b9 --- /dev/null +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_enums.py @@ -0,0 +1,302 @@ +# 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 enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccessPolicyAssignmentProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Provisioning state of an access policy assignment set.""" + + UPDATING = "Updating" + """The access policy assignments are being updated.""" + SUCCEEDED = "Succeeded" + """The access policy assignments were successfully updated.""" + DELETING = "Deleting" + """The access policy assignments are being deleted.""" + DELETED = "Deleted" + """The access policy assignments are considered deleted, meaning no custom access policies are + applied.""" + CANCELED = "Canceled" + """The operation was canceled. Access policy assignments may be in a partially updated state. + Update them again to have a well-defined state.""" + FAILED = "Failed" + """The operation failed. Access policy assignments may be in a partially updated state. Update + them again to have a well-defined state.""" + + +class AccessPolicyProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Provisioning state of access policy.""" + + UPDATING = "Updating" + """An operation is in progress.""" + SUCCEEDED = "Succeeded" + """The operation succeeded.""" + DELETING = "Deleting" + """A delete operation is in progress.""" + DELETED = "Deleted" + """The access policy is considered deleted, if it still exists.""" + CANCELED = "Canceled" + """The operation was canceled. Access policies may be in a partially updated state. Update them + again to have a well-defined state.""" + FAILED = "Failed" + """The operation failed. Access policies may be in a partially updated state. Update them again to + have a well-defined state.""" + + +class AccessPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Built-In or Custom access policy.""" + + CUSTOM = "Custom" + """User-configurable access policy, using the redis access policy authoring language.""" + BUILT_IN = "BuiltIn" + """Built-in or well-known access policies, whose policy is not configurable.""" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of entity that created the resource.""" + + USER = "User" + """The entity was created by a user.""" + APPLICATION = "Application" + """The entity was created by an application.""" + MANAGED_IDENTITY = "ManagedIdentity" + """The entity was created by a managed identity.""" + KEY = "Key" + """The entity was created by a key.""" + + +class DayOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Day of the week when a cache can be patched.""" + + MONDAY = "Monday" + """MONDAY.""" + TUESDAY = "Tuesday" + """TUESDAY.""" + WEDNESDAY = "Wednesday" + """WEDNESDAY.""" + THURSDAY = "Thursday" + """THURSDAY.""" + FRIDAY = "Friday" + """FRIDAY.""" + SATURDAY = "Saturday" + """SATURDAY.""" + SUNDAY = "Sunday" + """SUNDAY.""" + EVERYDAY = "Everyday" + """As a convenience, 'Everyday' is also accepted and means the same as specifying all days of the + week.""" + WEEKEND = "Weekend" + """As a convenience, 'Weekend' is also accepted and means the same as specifying Saturday and + Sunday.""" + + +class DefaultName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The name of the resource that is the target of a particular operation. For singleton resources, + it must be 'Default'. + """ + + DEFAULT = "default" + """The name of e.g. the patch schedules resource, which is a singleton, must always be 'Default'.""" + + +class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of managed service identity (where both SystemAssigned and UserAssigned types are + allowed). + """ + + NONE = "None" + """No managed identity.""" + SYSTEM_ASSIGNED = "SystemAssigned" + """System assigned managed identity.""" + USER_ASSIGNED = "UserAssigned" + """User assigned managed identity.""" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" + """System and user assigned managed identity.""" + + +class PrivateEndpointConnectionProvisioningState( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """The current provisioning state.""" + + SUCCEEDED = "Succeeded" + """Connection has been provisioned.""" + CREATING = "Creating" + """Connection is being created.""" + DELETING = "Deleting" + """Connection is being deleted.""" + FAILED = "Failed" + """Connection provisioning has failed.""" + + +class PrivateEndpointServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The private endpoint connection status.""" + + PENDING = "Pending" + """Connection waiting for approval or rejection.""" + APPROVED = "Approved" + """Connection approved.""" + REJECTED = "Rejected" + """Connection Rejected.""" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Redis instance provisioning status.""" + + CREATING = "Creating" + """A create operation is in progress.""" + DELETING = "Deleting" + """A delete operation is in progress.""" + DISABLED = "Disabled" + """The cache is disabled and cannot be used.""" + FAILED = "Failed" + """An operation such as create or update failed. If you failed to create the cache it will not be + in a usable state, so you should delete and recreate it.""" + LINKING = "Linking" + """Georeplication link is in progress.""" + PROVISIONING = "Provisioning" + """An operation is in progress.""" + RECOVERING_SCALE_FAILURE = "RecoveringScaleFailure" + """A scaling operation encountered an error and recovery is in progress.""" + SCALING = "Scaling" + """A scaling operation is in progress.""" + SUCCEEDED = "Succeeded" + """The most recent operation successfully completed.""" + UNLINKING = "Unlinking" + """Georeplication unlink is in progress.""" + UNPROVISIONING = "Unprovisioning" + """The cache may be being disabled.""" + UPDATING = "Updating" + """An update operation is in progress.""" + CONFIGURING_AAD = "ConfiguringAAD" + """An AAD configuration update operation is in progress.""" + MIGRATING = "Migrating" + """A migration to Azure Managed Redis is in progress.""" + MIGRATION_FAILED = "MigrationFailed" + """A migration to Azure Managed Redis failed.""" + MIGRATION_SUCCEEDED = "MigrationSucceeded" + """A migration to Azure Managed Redis succeeded.""" + MIGRATION_CANCELLING = "MigrationCancelling" + """A cancellation (rollback) of a migration to Azure Managed Redis is in progress.""" + MIGRATION_CANCELLATION_FAILED = "MigrationCancellationFailed" + """A cancellation (rollback) of a migration to Azure Managed Redis has failed.""" + + +class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Whether or not public endpoint access is allowed for this cache. Value is optional but if + passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private endpoints are the exclusive + access method. Default value is 'Enabled'. + """ + + ENABLED = "Enabled" + """Public internet access to the cache, via its public IP address, is enabled. Connections may use + any network path.""" + DISABLED = "Disabled" + """Public internet access to the cache, via its public IP address, is disabled. Connections must + use be made via private endpoints.""" + + +class RebootType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Which Redis node(s) to reboot. Depending on this value data loss is possible.""" + + PRIMARY_NODE = "PrimaryNode" + """Reboot the primary nodes used for redis write operations. (This may trigger role changes.).""" + SECONDARY_NODE = "SecondaryNode" + """Reboot only the secondary or replica nodes.""" + ALL_NODES = "AllNodes" + """Reboot all nodes, not guaranteed to happen simultaneously.""" + + +class RedisKeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The Redis access key to regenerate.""" + + PRIMARY = "Primary" + """The primary access key.""" + SECONDARY = "Secondary" + """The secondary access key.""" + + +class ReplicationRole(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Role of the linked server.""" + + PRIMARY = "Primary" + """The linked server is in the writable primary role.""" + SECONDARY = "Secondary" + """The linked server is in the read-only replica role.""" + + +class SkuFamily(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium).""" + + C = "C" + """The SKU family to use - must be 'C' for Basic/Standard SKU redis caches.""" + P = "P" + """The SKU family to use - must be 'P' for Premium SKU redis caches.""" + + +class SkuName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium).""" + + BASIC = "Basic" + """The well known 'Basic' SKU for Azure Cache for Redis. Basic SKU does not have an availability + SLA.""" + STANDARD = "Standard" + """The well known 'Standard' SKU for Azure Cache for Redis. Standard SKU has an availability SLA.""" + PREMIUM = "Premium" + """The well known 'Premium' SKU for Azure Cache for Redis. Premium SKU has an availability SLA, + and higher performance tiers and more features compared with Standard SKU.""" + + +class TlsVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', + '1.1', '1.2'). + """ + + ONE0 = "1.0" + """TLS protocol version 1.0 -- deprecated for security reasons. Do not use this value for new + caches.""" + ONE1 = "1.1" + """TLS protocol version 1.1 -- deprecated for security reasons. Do not use this value for new + caches.""" + ONE2 = "1.2" + """TLS protocol version 1.2 -- use this value, or higher, for new caches. Or do not specify, so + that your cache uses the recommended default value.""" + + +class UpdateChannel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Optional: Specifies the update channel for the monthly Redis updates your Redis Cache will + receive. Caches using 'Preview' update channel get latest Redis updates at least 4 weeks ahead + of 'Stable' channel caches. Default value is 'Stable'. + """ + + STABLE = "Stable" + """Stable channel receives updates, which may include important security and stability updates, + later than Preview channel.""" + PREVIEW = "Preview" + """Preview channel normally receives updates before Stable channel, and is the recommended channel + for non-production workloads.""" + + +class ZonalAllocationPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Optional: Specifies how availability zones are allocated to the Redis cache. 'Automatic' + enables zone redundancy and Azure will automatically select zones based on regional + availability and capacity. 'UserDefined' will select availability zones passed in by you using + the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If 'zonalAllocationPolicy' is + not passed, it will be set to 'UserDefined' when zones are passed in, otherwise, it will be set + to 'Automatic' in regions where zones are supported and 'NoZones' in regions where zones are + not supported. + """ + + AUTOMATIC = "Automatic" + """The zones for the cache will be selected automatically based on availability and capacity.""" + USER_DEFINED = "UserDefined" + """UserDefined means the zones for the cache are manually configured using the 'zones' property, + and can not be automatically selected.""" + NO_ZONES = "NoZones" + """The cache will not use multiple availability zones.""" diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_models.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_models.py new file mode 100644 index 000000000000..294cb9031097 --- /dev/null +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_models.py @@ -0,0 +1,2681 @@ +# 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, 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 CheckNameAvailabilityParameters(_Model): + """Parameters body to pass for resource name availability check. + + :ivar name: Resource name. Required. + :vartype name: str + :ivar type: Resource type. The only legal value of this property for checking redis cache name + availability is 'Microsoft.Cache/redis'. Required. + :vartype type: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource name. Required.""" + type: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource type. The only legal value of this property for checking redis cache name availability + is 'Microsoft.Cache/redis'. Required.""" + + @overload + def __init__( + self, + *, + name: str, + type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ErrorAdditionalInfo(_Model): + """The resource management error additional info. + + :ivar type: The additional info type. + :vartype type: str + :ivar info: The additional info. + :vartype info: any + """ + + type: Optional[str] = rest_field(visibility=["read"]) + """The additional info type.""" + info: Optional[Any] = rest_field(visibility=["read"]) + """The additional info.""" + + +class ErrorDetail(_Model): + """The error detail. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.redis.models.ErrorDetail] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.redis.models.ErrorAdditionalInfo] + """ + + code: Optional[str] = rest_field(visibility=["read"]) + """The error code.""" + message: Optional[str] = rest_field(visibility=["read"]) + """The error message.""" + target: Optional[str] = rest_field(visibility=["read"]) + """The error target.""" + details: Optional[list["_models.ErrorDetail"]] = rest_field(visibility=["read"]) + """The error details.""" + additional_info: Optional[list["_models.ErrorAdditionalInfo"]] = rest_field( + name="additionalInfo", visibility=["read"] + ) + """The error additional info.""" + + +class ErrorResponse(_Model): + """Error response. + + :ivar error: The error object. + :vartype error: ~azure.mgmt.redis.models.ErrorDetail + """ + + error: Optional["_models.ErrorDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error object.""" + + @overload + def __init__( + self, + *, + error: Optional["_models.ErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ExportRDBParameters(_Model): + """Parameters for Redis export operation. + + :ivar format: File format. + :vartype format: str + :ivar prefix: Prefix to use for exported files. Required. + :vartype prefix: str + :ivar container: Container name to export to. Required. + :vartype container: str + :ivar preferred_data_archive_auth_method: Preferred auth method to communicate to storage + account used for data archive, specify SAS or ManagedIdentity, default value is SAS. + :vartype preferred_data_archive_auth_method: str + :ivar storage_subscription_id: Subscription id of the storage container for data to be exported + using ManagedIdentity. + :vartype storage_subscription_id: str + """ + + format: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """File format.""" + prefix: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Prefix to use for exported files. Required.""" + container: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Container name to export to. Required.""" + preferred_data_archive_auth_method: Optional[str] = rest_field( + name="preferred-data-archive-auth-method", visibility=["read", "create", "update", "delete", "query"] + ) + """Preferred auth method to communicate to storage account used for data archive, specify SAS or + ManagedIdentity, default value is SAS.""" + storage_subscription_id: Optional[str] = rest_field( + name="storage-subscription-id", visibility=["read", "create", "update", "delete", "query"] + ) + """Subscription id of the storage container for data to be exported using ManagedIdentity.""" + + @overload + def __init__( + self, + *, + prefix: str, + container: str, + format: Optional[str] = None, + preferred_data_archive_auth_method: Optional[str] = None, + storage_subscription_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 ImportRDBParameters(_Model): + """Parameters for Redis import operation. + + :ivar format: File format. + :vartype format: str + :ivar files: files to import. Required. + :vartype files: list[str] + :ivar preferred_data_archive_auth_method: Preferred auth method to communicate to storage + account used for data archive, specify SAS or ManagedIdentity, default value is SAS. + :vartype preferred_data_archive_auth_method: str + :ivar storage_subscription_id: Subscription id of the storage container containing files to + import using Managed Identity. + :vartype storage_subscription_id: str + """ + + format: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """File format.""" + files: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """files to import. Required.""" + preferred_data_archive_auth_method: Optional[str] = rest_field( + name="preferred-data-archive-auth-method", visibility=["read", "create", "update", "delete", "query"] + ) + """Preferred auth method to communicate to storage account used for data archive, specify SAS or + ManagedIdentity, default value is SAS.""" + storage_subscription_id: Optional[str] = rest_field( + name="storage-subscription-id", visibility=["read", "create", "update", "delete", "query"] + ) + """Subscription id of the storage container containing files to import using Managed Identity.""" + + @overload + def __init__( + self, + *, + files: list[str], + format: Optional[str] = None, + preferred_data_archive_auth_method: Optional[str] = None, + storage_subscription_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 ManagedServiceIdentity(_Model): + """Managed service identity (system assigned and/or user assigned identities). + + :ivar principal_id: The service principal ID of the system assigned identity. This property + will only be provided for a system assigned identity. + :vartype principal_id: str + :ivar tenant_id: The tenant ID of the system assigned identity. This property will only be + provided for a system assigned identity. + :vartype tenant_id: str + :ivar type: The type of managed identity assigned to this resource. Required. Known values are: + "None", "SystemAssigned", "UserAssigned", and "SystemAssigned, UserAssigned". + :vartype type: str or ~azure.mgmt.redis.models.ManagedServiceIdentityType + :ivar user_assigned_identities: The identities assigned to this resource by the user. + :vartype user_assigned_identities: dict[str, ~azure.mgmt.redis.models.UserAssignedIdentity] + """ + + principal_id: Optional[str] = rest_field(name="principalId", visibility=["read"]) + """The service principal ID of the system assigned identity. This property will only be provided + for a system assigned identity.""" + tenant_id: Optional[str] = rest_field(name="tenantId", visibility=["read"]) + """The tenant ID of the system assigned identity. This property will only be provided for a system + assigned identity.""" + type: Union[str, "_models.ManagedServiceIdentityType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The type of managed identity assigned to this resource. Required. Known values are: \"None\", + \"SystemAssigned\", \"UserAssigned\", and \"SystemAssigned, UserAssigned\".""" + user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentity"]] = rest_field( + name="userAssignedIdentities", visibility=["read", "create", "update", "delete", "query"] + ) + """The identities assigned to this resource by the user.""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.ManagedServiceIdentityType"], + user_assigned_identities: Optional[dict[str, "_models.UserAssignedIdentity"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Operation(_Model): + """REST API operation. + + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The object that describes the operation. + :vartype display: ~azure.mgmt.redis.models.OperationDisplay + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Operation name: {provider}/{resource}/{operation}.""" + display: Optional["_models.OperationDisplay"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The object that describes the operation.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["_models.OperationDisplay"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class OperationDisplay(_Model): + """The object that describes the operation. + + :ivar provider: Friendly name of the resource provider. + :vartype provider: str + :ivar operation: Operation type: read, write, delete, listKeys/action, etc. + :vartype operation: str + :ivar resource: Resource type on which the operation is performed. + :vartype resource: str + :ivar description: Friendly name of the operation. + :vartype description: str + """ + + provider: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Friendly name of the resource provider.""" + operation: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Operation type: read, write, delete, listKeys/action, etc.""" + resource: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource type on which the operation is performed.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Friendly name of the operation.""" + + @overload + def __init__( + self, + *, + provider: Optional[str] = None, + operation: Optional[str] = None, + resource: 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 OperationStatusResult(_Model): + """The current status of an async operation. + + :ivar id: Fully qualified ID for the async operation. + :vartype id: str + :ivar name: Name of the async operation. + :vartype name: str + :ivar status: Operation status. Required. + :vartype status: str + :ivar percent_complete: Percent of the operation that is complete. + :vartype percent_complete: float + :ivar start_time: The start time of the operation. + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time of the operation. + :vartype end_time: ~datetime.datetime + :ivar operations: The operations list. + :vartype operations: list[~azure.mgmt.redis.models.OperationStatusResult] + :ivar error: If present, details of the operation error. + :vartype error: ~azure.mgmt.redis.models.ErrorDetail + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Fully qualified ID for the async operation.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the async operation.""" + status: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Operation status. Required.""" + percent_complete: Optional[float] = rest_field( + name="percentComplete", visibility=["read", "create", "update", "delete", "query"] + ) + """Percent of the operation that is complete.""" + start_time: Optional[datetime.datetime] = rest_field( + name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start time of the operation.""" + end_time: Optional[datetime.datetime] = rest_field( + name="endTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end time of the operation.""" + operations: Optional[list["_models.OperationStatusResult"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The operations list.""" + error: Optional["_models.ErrorDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """If present, details of the operation error.""" + + @overload + def __init__( + self, + *, + status: str, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + percent_complete: Optional[float] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + operations: Optional[list["_models.OperationStatusResult"]] = None, + error: Optional["_models.ErrorDetail"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class OperationStatus(OperationStatusResult): + """Asynchronous operation status. + + :ivar id: Fully qualified ID for the async operation. + :vartype id: str + :ivar name: Name of the async operation. + :vartype name: str + :ivar status: Operation status. Required. + :vartype status: str + :ivar percent_complete: Percent of the operation that is complete. + :vartype percent_complete: float + :ivar start_time: The start time of the operation. + :vartype start_time: ~datetime.datetime + :ivar end_time: The end time of the operation. + :vartype end_time: ~datetime.datetime + :ivar operations: The operations list. + :vartype operations: list[~azure.mgmt.redis.models.OperationStatusResult] + :ivar error: If present, details of the operation error. + :vartype error: ~azure.mgmt.redis.models.ErrorDetail + :ivar properties: Additional properties from RP, only when operation is successful. + :vartype properties: dict[str, any] + """ + + properties: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional properties from RP, only when operation is successful.""" + + @overload + def __init__( + self, + *, + status: str, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + percent_complete: Optional[float] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + operations: Optional[list["_models.OperationStatusResult"]] = None, + error: Optional["_models.ErrorDetail"] = None, + properties: Optional[dict[str, 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 PrivateEndpoint(_Model): + """The private endpoint resource. + + :ivar id: The resource identifier of the private endpoint. + :vartype id: str + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """The resource identifier of the private endpoint.""" + + +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.redis.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 PrivateEndpointConnection(Resource): + """The Private Endpoint Connection 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.redis.models.SystemData + :ivar properties: Resource properties. + :vartype properties: ~azure.mgmt.redis.models.PrivateEndpointConnectionProperties + """ + + properties: Optional["_models.PrivateEndpointConnectionProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Resource properties.""" + + __flattened_items = ["group_ids", "private_endpoint", "private_link_service_connection_state", "provisioning_state"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.PrivateEndpointConnectionProperties"] = 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 PrivateEndpointConnectionProperties(_Model): + """Properties of the private endpoint connection. + + :ivar group_ids: The group ids for the private endpoint resource. + :vartype group_ids: list[str] + :ivar private_endpoint: The private endpoint resource. + :vartype private_endpoint: ~azure.mgmt.redis.models.PrivateEndpoint + :ivar private_link_service_connection_state: A collection of information about the state of the + connection between service consumer and provider. Required. + :vartype private_link_service_connection_state: + ~azure.mgmt.redis.models.PrivateLinkServiceConnectionState + :ivar provisioning_state: The provisioning state of the private endpoint connection resource. + Known values are: "Succeeded", "Creating", "Deleting", and "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.redis.models.PrivateEndpointConnectionProvisioningState + """ + + group_ids: Optional[list[str]] = rest_field(name="groupIds", visibility=["read"]) + """The group ids for the private endpoint resource.""" + private_endpoint: Optional["_models.PrivateEndpoint"] = rest_field( + name="privateEndpoint", visibility=["read", "create", "update", "delete", "query"] + ) + """The private endpoint resource.""" + private_link_service_connection_state: "_models.PrivateLinkServiceConnectionState" = rest_field( + name="privateLinkServiceConnectionState", visibility=["read", "create", "update", "delete", "query"] + ) + """A collection of information about the state of the connection between service consumer and + provider. Required.""" + provisioning_state: Optional[Union[str, "_models.PrivateEndpointConnectionProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """The provisioning state of the private endpoint connection resource. Known values are: + \"Succeeded\", \"Creating\", \"Deleting\", and \"Failed\".""" + + @overload + def __init__( + self, + *, + private_link_service_connection_state: "_models.PrivateLinkServiceConnectionState", + private_endpoint: Optional["_models.PrivateEndpoint"] = 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 PrivateLinkResource(Resource): + """A private link 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.redis.models.SystemData + :ivar properties: Resource properties. + :vartype properties: ~azure.mgmt.redis.models.PrivateLinkResourceProperties + """ + + properties: Optional["_models.PrivateLinkResourceProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Resource properties.""" + + @overload + def __init__( + self, + *, + properties: Optional["_models.PrivateLinkResourceProperties"] = 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 PrivateLinkResourceProperties(_Model): + """Properties of a private link resource. + + :ivar group_id: The private link resource group id. + :vartype group_id: str + :ivar required_members: The private link resource required member names. + :vartype required_members: list[str] + :ivar required_zone_names: The private link resource private link DNS zone name. + :vartype required_zone_names: list[str] + """ + + group_id: Optional[str] = rest_field(name="groupId", visibility=["read"]) + """The private link resource group id.""" + required_members: Optional[list[str]] = rest_field(name="requiredMembers", visibility=["read"]) + """The private link resource required member names.""" + required_zone_names: Optional[list[str]] = rest_field( + name="requiredZoneNames", visibility=["read", "create", "update", "delete", "query"] + ) + """The private link resource private link DNS zone name.""" + + @overload + def __init__( + self, + *, + required_zone_names: 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 PrivateLinkServiceConnectionState(_Model): + """A collection of information about the state of the connection between service consumer and + provider. + + :ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner + of the service. Known values are: "Pending", "Approved", and "Rejected". + :vartype status: str or ~azure.mgmt.redis.models.PrivateEndpointServiceConnectionStatus + :ivar description: The reason for approval/rejection of the connection. + :vartype description: str + :ivar actions_required: A message indicating if changes on the service provider require any + updates on the consumer. + :vartype actions_required: str + """ + + status: Optional[Union[str, "_models.PrivateEndpointServiceConnectionStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Indicates whether the connection has been Approved/Rejected/Removed by the owner of the + service. Known values are: \"Pending\", \"Approved\", and \"Rejected\".""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The reason for approval/rejection of the connection.""" + actions_required: Optional[str] = rest_field( + name="actionsRequired", visibility=["read", "create", "update", "delete", "query"] + ) + """A message indicating if changes on the service provider require any updates on the consumer.""" + + @overload + def __init__( + self, + *, + status: Optional[Union[str, "_models.PrivateEndpointServiceConnectionStatus"]] = None, + description: Optional[str] = None, + actions_required: 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 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.redis.models.SystemData + """ + + +class RedisAccessKeys(_Model): + """Redis cache access keys. + + :ivar primary_key: The current primary key that clients can use to authenticate with Redis + cache. + :vartype primary_key: str + :ivar secondary_key: The current secondary key that clients can use to authenticate with Redis + cache. + :vartype secondary_key: str + """ + + primary_key: Optional[str] = rest_field(name="primaryKey", visibility=["read"]) + """The current primary key that clients can use to authenticate with Redis cache.""" + secondary_key: Optional[str] = rest_field(name="secondaryKey", visibility=["read"]) + """The current secondary key that clients can use to authenticate with Redis cache.""" + + +class RedisCacheAccessPolicy(ProxyResource): + """Response to get/put access policy. + + :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.redis.models.SystemData + :ivar properties: Properties of an access policy. + :vartype properties: ~azure.mgmt.redis.models.RedisCacheAccessPolicyProperties + """ + + properties: Optional["_models.RedisCacheAccessPolicyProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of an access policy.""" + + __flattened_items = ["provisioning_state", "type", "permissions"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.RedisCacheAccessPolicyProperties"] = 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 RedisCacheAccessPolicyAssignment(ProxyResource): + """Response to an operation on access policy assignment. + + :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.redis.models.SystemData + :ivar properties: Properties of an access policy assignment. + :vartype properties: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignmentProperties + """ + + properties: Optional["_models.RedisCacheAccessPolicyAssignmentProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of an access policy assignment.""" + + __flattened_items = ["provisioning_state", "object_id", "object_id_alias", "access_policy_name"] + + @overload + def __init__( + self, + *, + properties: Optional["_models.RedisCacheAccessPolicyAssignmentProperties"] = 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 RedisCacheAccessPolicyAssignmentProperties(_Model): # pylint: disable=name-too-long + """Properties for an access policy assignment. + + :ivar provisioning_state: Provisioning state of an access policy assignment set. Known values + are: "Updating", "Succeeded", "Deleting", "Deleted", "Canceled", and "Failed". + :vartype provisioning_state: str or + ~azure.mgmt.redis.models.AccessPolicyAssignmentProvisioningState + :ivar object_id: Object Id to assign access policy to. Required. + :vartype object_id: str + :ivar object_id_alias: User friendly name for object id. Also represents username for token + based authentication. Required. + :vartype object_id_alias: str + :ivar access_policy_name: The name of the access policy that is being assigned. Required. + :vartype access_policy_name: str + """ + + provisioning_state: Optional[Union[str, "_models.AccessPolicyAssignmentProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """Provisioning state of an access policy assignment set. Known values are: \"Updating\", + \"Succeeded\", \"Deleting\", \"Deleted\", \"Canceled\", and \"Failed\".""" + object_id: str = rest_field(name="objectId", visibility=["read", "create", "update", "delete", "query"]) + """Object Id to assign access policy to. Required.""" + object_id_alias: str = rest_field(name="objectIdAlias", visibility=["read", "create", "update", "delete", "query"]) + """User friendly name for object id. Also represents username for token based authentication. + Required.""" + access_policy_name: str = rest_field( + name="accessPolicyName", visibility=["read", "create", "update", "delete", "query"] + ) + """The name of the access policy that is being assigned. Required.""" + + @overload + def __init__( + self, + *, + object_id: str, + object_id_alias: str, + access_policy_name: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RedisCacheAccessPolicyProperties(_Model): + """All properties of an access policy. + + :ivar provisioning_state: Provisioning state of access policy. Known values are: "Updating", + "Succeeded", "Deleting", "Deleted", "Canceled", and "Failed". + :vartype provisioning_state: str or ~azure.mgmt.redis.models.AccessPolicyProvisioningState + :ivar type: Built-In or Custom access policy. Known values are: "Custom" and "BuiltIn". + :vartype type: str or ~azure.mgmt.redis.models.AccessPolicyType + :ivar permissions: Permissions for the access policy. Learn how to configure permissions at + `https://aka.ms/redis/AADPreRequisites `_. Required. + :vartype permissions: str + """ + + provisioning_state: Optional[Union[str, "_models.AccessPolicyProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """Provisioning state of access policy. Known values are: \"Updating\", \"Succeeded\", + \"Deleting\", \"Deleted\", \"Canceled\", and \"Failed\".""" + type: Optional[Union[str, "_models.AccessPolicyType"]] = rest_field(visibility=["read"]) + """Built-In or Custom access policy. Known values are: \"Custom\" and \"BuiltIn\".""" + permissions: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Permissions for the access policy. Learn how to configure permissions at + `https://aka.ms/redis/AADPreRequisites `_. Required.""" + + @overload + def __init__( + self, + *, + permissions: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RedisCommonProperties(_Model): + """Create/Update/Get common properties of the redis cache. + + :ivar redis_configuration: All Redis Settings. Few possible keys: + rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, + maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, + aof-storage-connection-string-1 etc. + :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration + :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is + required) or the value 'latest' which refers to the latest stable Redis version that is + available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. + :vartype redis_version: str + :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. + :vartype enable_non_ssl_port: bool + :ivar replicas_per_master: The number of replicas to be created per primary. + :vartype replicas_per_master: int + :ivar replicas_per_primary: The number of replicas to be created per primary. + :vartype replicas_per_primary: int + :ivar tenant_settings: A dictionary of tenant settings. + :vartype tenant_settings: dict[str, str] + :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. + :vartype shard_count: int + :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or + higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". + :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion + :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private + endpoints are the exclusive access method. Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess + :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your + Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at + least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: + "Stable" and "Preview". + :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel + :ivar disable_access_key_authentication: Authentication to Redis through access keys is + disabled when set as true. Default value is false. + :vartype disable_access_key_authentication: bool + :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the + Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones + based on regional availability and capacity. 'UserDefined' will select availability zones + passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If + 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed + in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' + in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and + "NoZones". + :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy + """ + + redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = rest_field( + name="redisConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """All Redis Settings. Few possible keys: + rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, + maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, + aof-storage-connection-string-1 etc.""" + redis_version: Optional[str] = rest_field( + name="redisVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """Redis version. This should be in the form 'major[.minor]' (only 'major' is required) or the + value 'latest' which refers to the latest stable Redis version that is available. Supported + versions: 4.0, 6.0 (latest). Default value is 'latest'.""" + enable_non_ssl_port: Optional[bool] = rest_field( + name="enableNonSslPort", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies whether the non-ssl Redis server port (6379) is enabled.""" + replicas_per_master: Optional[int] = rest_field( + name="replicasPerMaster", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of replicas to be created per primary.""" + replicas_per_primary: Optional[int] = rest_field( + name="replicasPerPrimary", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of replicas to be created per primary.""" + tenant_settings: Optional[dict[str, str]] = rest_field( + name="tenantSettings", visibility=["read", "create", "update", "delete", "query"] + ) + """A dictionary of tenant settings.""" + shard_count: Optional[int] = rest_field( + name="shardCount", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of shards to be created on a Premium Cluster Cache.""" + minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = rest_field( + name="minimumTlsVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', + '1.1', '1.2'). Known values are: \"1.0\", \"1.1\", and \"1.2\".""" + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = rest_field( + name="publicNetworkAccess", visibility=["read", "create", "update", "delete", "query"] + ) + """Whether or not public endpoint access is allowed for this cache. Value is optional but if + passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private endpoints are the exclusive + access method. Known values are: \"Enabled\" and \"Disabled\".""" + update_channel: Optional[Union[str, "_models.UpdateChannel"]] = rest_field( + name="updateChannel", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional: Specifies the update channel for the monthly Redis updates your Redis Cache will + receive. Caches using 'Preview' update channel get latest Redis updates at least 4 weeks ahead + of 'Stable' channel caches. Default value is 'Stable'. Known values are: \"Stable\" and + \"Preview\".""" + disable_access_key_authentication: Optional[bool] = rest_field( + name="disableAccessKeyAuthentication", visibility=["read", "create", "update", "delete", "query"] + ) + """Authentication to Redis through access keys is disabled when set as true. Default value is + false.""" + zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = rest_field( + name="zonalAllocationPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional: Specifies how availability zones are allocated to the Redis cache. 'Automatic' + enables zone redundancy and Azure will automatically select zones based on regional + availability and capacity. 'UserDefined' will select availability zones passed in by you using + the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If 'zonalAllocationPolicy' is + not passed, it will be set to 'UserDefined' when zones are passed in, otherwise, it will be set + to 'Automatic' in regions where zones are supported and 'NoZones' in regions where zones are + not supported. Known values are: \"Automatic\", \"UserDefined\", and \"NoZones\".""" + + @overload + def __init__( + self, + *, + redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, + redis_version: Optional[str] = None, + enable_non_ssl_port: Optional[bool] = None, + replicas_per_master: Optional[int] = None, + replicas_per_primary: Optional[int] = None, + tenant_settings: Optional[dict[str, str]] = None, + shard_count: Optional[int] = None, + minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, + disable_access_key_authentication: Optional[bool] = None, + zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = 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 RedisCommonPropertiesRedisConfiguration(_Model): + """All Redis Settings. Few possible keys: + rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, + maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, + aof-storage-connection-string-1 etc. + + :ivar rdb_backup_enabled: Specifies whether the RDB backup is enabled. + :vartype rdb_backup_enabled: str + :ivar rdb_backup_frequency: Specifies the frequency for creating rdb backup in minutes. Valid + values: (15, 30, 60, 360, 720, 1440). + :vartype rdb_backup_frequency: str + :ivar rdb_backup_max_snapshot_count: Specifies the maximum number of snapshots for rdb backup. + :vartype rdb_backup_max_snapshot_count: str + :ivar rdb_storage_connection_string: The storage account connection string for storing rdb + file. + :vartype rdb_storage_connection_string: str + :ivar aof_backup_enabled: Specifies whether the aof backup is enabled. + :vartype aof_backup_enabled: str + :ivar aof_storage_connection_string0: First storage account connection string. + :vartype aof_storage_connection_string0: str + :ivar aof_storage_connection_string1: Second storage account connection string. + :vartype aof_storage_connection_string1: str + :ivar maxfragmentationmemory_reserved: Value in megabytes reserved for fragmentation per shard. + :vartype maxfragmentationmemory_reserved: str + :ivar maxmemory_policy: The eviction strategy used when your data won't fit within its memory + limit. + :vartype maxmemory_policy: str + :ivar maxmemory_reserved: Value in megabytes reserved for non-cache usage per shard e.g. + failover. + :vartype maxmemory_reserved: str + :ivar maxmemory_delta: Value in megabytes reserved for non-cache usage per shard e.g. failover. + :vartype maxmemory_delta: str + :ivar maxclients: The max clients config. + :vartype maxclients: str + :ivar notify_keyspace_events: The keyspace events which should be monitored. + :vartype notify_keyspace_events: str + :ivar preferred_data_archive_auth_method: Preferred auth method to communicate to storage + account used for data archive, specify SAS or ManagedIdentity, default value is SAS. + :vartype preferred_data_archive_auth_method: str + :ivar preferred_data_persistence_auth_method: Preferred auth method to communicate to storage + account used for data persistence, specify SAS or ManagedIdentity, default value is SAS. + :vartype preferred_data_persistence_auth_method: str + :ivar zonal_configuration: Zonal Configuration. + :vartype zonal_configuration: str + :ivar authnotrequired: Specifies whether the authentication is disabled. Setting this property + is highly discouraged from security point of view; you should never disable authentication + using this property!. + :vartype authnotrequired: str + :ivar storage_subscription_id: SubscriptionId of the storage account for persistence (aof/rdb) + using ManagedIdentity. + :vartype storage_subscription_id: str + :ivar aad_enabled: Specifies whether AAD based authentication has been enabled or disabled for + the cache. + :vartype aad_enabled: str + """ + + rdb_backup_enabled: Optional[str] = rest_field( + name="rdb-backup-enabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies whether the RDB backup is enabled.""" + rdb_backup_frequency: Optional[str] = rest_field( + name="rdb-backup-frequency", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the frequency for creating rdb backup in minutes. Valid values: (15, 30, 60, 360, + 720, 1440).""" + rdb_backup_max_snapshot_count: Optional[str] = rest_field( + name="rdb-backup-max-snapshot-count", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the maximum number of snapshots for rdb backup.""" + rdb_storage_connection_string: Optional[str] = rest_field( + name="rdb-storage-connection-string", visibility=["read", "create", "update", "delete", "query"] + ) + """The storage account connection string for storing rdb file.""" + aof_backup_enabled: Optional[str] = rest_field( + name="aof-backup-enabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies whether the aof backup is enabled.""" + aof_storage_connection_string0: Optional[str] = rest_field( + name="aof-storage-connection-string-0", visibility=["read", "create", "update", "delete", "query"] + ) + """First storage account connection string.""" + aof_storage_connection_string1: Optional[str] = rest_field( + name="aof-storage-connection-string-1", visibility=["read", "create", "update", "delete", "query"] + ) + """Second storage account connection string.""" + maxfragmentationmemory_reserved: Optional[str] = rest_field( + name="maxfragmentationmemory-reserved", visibility=["read", "create", "update", "delete", "query"] + ) + """Value in megabytes reserved for fragmentation per shard.""" + maxmemory_policy: Optional[str] = rest_field( + name="maxmemory-policy", visibility=["read", "create", "update", "delete", "query"] + ) + """The eviction strategy used when your data won't fit within its memory limit.""" + maxmemory_reserved: Optional[str] = rest_field( + name="maxmemory-reserved", visibility=["read", "create", "update", "delete", "query"] + ) + """Value in megabytes reserved for non-cache usage per shard e.g. failover.""" + maxmemory_delta: Optional[str] = rest_field( + name="maxmemory-delta", visibility=["read", "create", "update", "delete", "query"] + ) + """Value in megabytes reserved for non-cache usage per shard e.g. failover.""" + maxclients: Optional[str] = rest_field(visibility=["read"]) + """The max clients config.""" + notify_keyspace_events: Optional[str] = rest_field( + name="notify-keyspace-events", visibility=["read", "create", "update", "delete", "query"] + ) + """The keyspace events which should be monitored.""" + preferred_data_archive_auth_method: Optional[str] = rest_field( + name="preferred-data-archive-auth-method", visibility=["read"] + ) + """Preferred auth method to communicate to storage account used for data archive, specify SAS or + ManagedIdentity, default value is SAS.""" + preferred_data_persistence_auth_method: Optional[str] = rest_field( + name="preferred-data-persistence-auth-method", visibility=["read", "create", "update", "delete", "query"] + ) + """Preferred auth method to communicate to storage account used for data persistence, specify SAS + or ManagedIdentity, default value is SAS.""" + zonal_configuration: Optional[str] = rest_field(name="zonal-configuration", visibility=["read"]) + """Zonal Configuration.""" + authnotrequired: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specifies whether the authentication is disabled. Setting this property is highly discouraged + from security point of view; you should never disable authentication using this property!.""" + storage_subscription_id: Optional[str] = rest_field( + name="storage-subscription-id", visibility=["read", "create", "update", "delete", "query"] + ) + """SubscriptionId of the storage account for persistence (aof/rdb) using ManagedIdentity.""" + aad_enabled: Optional[str] = rest_field( + name="aad-enabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies whether AAD based authentication has been enabled or disabled for the cache.""" + + @overload + def __init__( + self, + *, + rdb_backup_enabled: Optional[str] = None, + rdb_backup_frequency: Optional[str] = None, + rdb_backup_max_snapshot_count: Optional[str] = None, + rdb_storage_connection_string: Optional[str] = None, + aof_backup_enabled: Optional[str] = None, + aof_storage_connection_string0: Optional[str] = None, + aof_storage_connection_string1: Optional[str] = None, + maxfragmentationmemory_reserved: Optional[str] = None, + maxmemory_policy: Optional[str] = None, + maxmemory_reserved: Optional[str] = None, + maxmemory_delta: Optional[str] = None, + notify_keyspace_events: Optional[str] = None, + preferred_data_persistence_auth_method: Optional[str] = None, + authnotrequired: Optional[str] = None, + storage_subscription_id: Optional[str] = None, + aad_enabled: 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 RedisCreateParameters(_Model): + """Parameters supplied to the Create Redis operation. + + :ivar properties: Redis cache properties. Required. + :vartype properties: ~azure.mgmt.redis.models.RedisCreateProperties + :ivar zones: A list of availability zones denoting where the resource needs to come from. + :vartype zones: list[str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar identity: The identity of the resource. + :vartype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity + """ + + properties: "_models.RedisCreateProperties" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Redis cache properties. Required.""" + zones: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of availability zones denoting where the resource needs to come from.""" + location: str = rest_field(visibility=["read", "create"]) + """The geo-location where the resource lives. Required.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource tags.""" + identity: Optional["_models.ManagedServiceIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The identity of the resource.""" + + __flattened_items = [ + "redis_configuration", + "redis_version", + "enable_non_ssl_port", + "replicas_per_master", + "replicas_per_primary", + "tenant_settings", + "shard_count", + "minimum_tls_version", + "public_network_access", + "update_channel", + "disable_access_key_authentication", + "zonal_allocation_policy", + "sku", + "subnet_id", + "static_ip", + ] + + @overload + def __init__( + self, + *, + properties: "_models.RedisCreateProperties", + location: str, + zones: Optional[list[str]] = None, + tags: Optional[dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = 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 RedisCreateProperties(RedisCommonProperties): + """Properties supplied to Create Redis operation. + + :ivar redis_configuration: All Redis Settings. Few possible keys: + rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, + maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, + aof-storage-connection-string-1 etc. + :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration + :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is + required) or the value 'latest' which refers to the latest stable Redis version that is + available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. + :vartype redis_version: str + :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. + :vartype enable_non_ssl_port: bool + :ivar replicas_per_master: The number of replicas to be created per primary. + :vartype replicas_per_master: int + :ivar replicas_per_primary: The number of replicas to be created per primary. + :vartype replicas_per_primary: int + :ivar tenant_settings: A dictionary of tenant settings. + :vartype tenant_settings: dict[str, str] + :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. + :vartype shard_count: int + :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or + higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". + :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion + :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private + endpoints are the exclusive access method. Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess + :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your + Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at + least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: + "Stable" and "Preview". + :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel + :ivar disable_access_key_authentication: Authentication to Redis through access keys is + disabled when set as true. Default value is false. + :vartype disable_access_key_authentication: bool + :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the + Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones + based on regional availability and capacity. 'UserDefined' will select availability zones + passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If + 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed + in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' + in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and + "NoZones". + :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy + :ivar sku: The SKU of the Redis cache to deploy. Required. + :vartype sku: ~azure.mgmt.redis.models.Sku + :ivar subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis + cache in. Example format: + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. + :vartype subnet_id: str + :ivar static_ip: Static IP address. Optionally, may be specified when deploying a Redis cache + inside an existing Azure Virtual Network; auto assigned by default. + :vartype static_ip: str + """ + + sku: "_models.Sku" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The SKU of the Redis cache to deploy. Required.""" + subnet_id: Optional[str] = rest_field(name="subnetId", visibility=["read", "create", "update", "delete", "query"]) + """The full resource ID of a subnet in a virtual network to deploy the Redis cache in. Example + format: + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1.""" + static_ip: Optional[str] = rest_field(name="staticIP", visibility=["read", "create"]) + """Static IP address. Optionally, may be specified when deploying a Redis cache inside an existing + Azure Virtual Network; auto assigned by default.""" + + @overload + def __init__( + self, + *, + sku: "_models.Sku", + redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, + redis_version: Optional[str] = None, + enable_non_ssl_port: Optional[bool] = None, + replicas_per_master: Optional[int] = None, + replicas_per_primary: Optional[int] = None, + tenant_settings: Optional[dict[str, str]] = None, + shard_count: Optional[int] = None, + minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, + disable_access_key_authentication: Optional[bool] = None, + zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, + subnet_id: Optional[str] = None, + static_ip: 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 RedisFirewallRule(ProxyResource): + """A firewall rule on a redis cache has a name, and describes a contiguous range of IP addresses + permitted to connect. + + :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.redis.models.SystemData + :ivar properties: redis cache firewall rule properties. Required. + :vartype properties: ~azure.mgmt.redis.models.RedisFirewallRuleProperties + """ + + properties: "_models.RedisFirewallRuleProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """redis cache firewall rule properties. Required.""" + + __flattened_items = ["start_ip", "end_ip"] + + @overload + def __init__( + self, + *, + properties: "_models.RedisFirewallRuleProperties", + ) -> 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 RedisFirewallRuleProperties(_Model): + """Specifies a range of IP addresses permitted to connect to the cache. + + :ivar start_ip: lowest IP address included in the range. Required. + :vartype start_ip: str + :ivar end_ip: highest IP address included in the range. Required. + :vartype end_ip: str + """ + + start_ip: str = rest_field(name="startIP", visibility=["read", "create", "update", "delete", "query"]) + """lowest IP address included in the range. Required.""" + end_ip: str = rest_field(name="endIP", visibility=["read", "create", "update", "delete", "query"]) + """highest IP address included in the range. Required.""" + + @overload + def __init__( + self, + *, + start_ip: str, + end_ip: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RedisForceRebootResponse(_Model): + """Response to force reboot for Redis cache. + + :ivar message: Status message. + :vartype message: str + """ + + message: Optional[str] = rest_field(visibility=["read"]) + """Status message.""" + + +class RedisInstanceDetails(_Model): + """Details of single instance of redis. + + :ivar ssl_port: Redis instance SSL port. + :vartype ssl_port: int + :ivar non_ssl_port: If enableNonSslPort is true, provides Redis instance Non-SSL port. + :vartype non_ssl_port: int + :ivar zone: If the Cache uses availability zones, specifies availability zone where this + instance is located. + :vartype zone: str + :ivar shard_id: If clustering is enabled, the Shard ID of Redis Instance. + :vartype shard_id: int + :ivar is_master: Specifies whether the instance is a primary node. + :vartype is_master: bool + :ivar is_primary: Specifies whether the instance is a primary node. + :vartype is_primary: bool + """ + + ssl_port: Optional[int] = rest_field(name="sslPort", visibility=["read"]) + """Redis instance SSL port.""" + non_ssl_port: Optional[int] = rest_field(name="nonSslPort", visibility=["read"]) + """If enableNonSslPort is true, provides Redis instance Non-SSL port.""" + zone: Optional[str] = rest_field(visibility=["read"]) + """If the Cache uses availability zones, specifies availability zone where this instance is + located.""" + shard_id: Optional[int] = rest_field(name="shardId", visibility=["read"]) + """If clustering is enabled, the Shard ID of Redis Instance.""" + is_master: Optional[bool] = rest_field(name="isMaster", visibility=["read"]) + """Specifies whether the instance is a primary node.""" + is_primary: Optional[bool] = rest_field(name="isPrimary", visibility=["read"]) + """Specifies whether the instance is a primary node.""" + + +class RedisLinkedServer(_Model): + """Linked server Id. + + :ivar id: Linked server Id. + :vartype id: str + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Linked server Id.""" + + +class RedisLinkedServerCreateParameters(_Model): + """Parameter required for creating a linked server to redis cache. + + :ivar properties: Properties required to create a linked server. Required. + :vartype properties: ~azure.mgmt.redis.models.RedisLinkedServerCreateProperties + """ + + properties: "_models.RedisLinkedServerCreateProperties" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties required to create a linked server. Required.""" + + __flattened_items = [ + "linked_redis_cache_id", + "linked_redis_cache_location", + "server_role", + "geo_replicated_primary_host_name", + "primary_host_name", + ] + + @overload + def __init__( + self, + *, + properties: "_models.RedisLinkedServerCreateProperties", + ) -> 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 RedisLinkedServerCreateProperties(_Model): + """Create properties for a linked server. + + :ivar linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. + :vartype linked_redis_cache_id: str + :ivar linked_redis_cache_location: Location of the linked redis cache. Required. + :vartype linked_redis_cache_location: str + :ivar server_role: Role of the linked server. Required. Known values are: "Primary" and + "Secondary". + :vartype server_role: str or ~azure.mgmt.redis.models.ReplicationRole + :ivar geo_replicated_primary_host_name: The unchanging DNS name which will always point to + current geo-primary cache among the linked redis caches for seamless Geo Failover experience. + :vartype geo_replicated_primary_host_name: str + :ivar primary_host_name: The changing DNS name that resolves to the current geo-primary cache + among the linked redis caches before or after the Geo Failover. + :vartype primary_host_name: str + """ + + linked_redis_cache_id: str = rest_field( + name="linkedRedisCacheId", visibility=["read", "create", "update", "delete", "query"] + ) + """Fully qualified resourceId of the linked redis cache. Required.""" + linked_redis_cache_location: str = rest_field(name="linkedRedisCacheLocation", visibility=["read", "create"]) + """Location of the linked redis cache. Required.""" + server_role: Union[str, "_models.ReplicationRole"] = rest_field( + name="serverRole", visibility=["read", "create", "update", "delete", "query"] + ) + """Role of the linked server. Required. Known values are: \"Primary\" and \"Secondary\".""" + geo_replicated_primary_host_name: Optional[str] = rest_field( + name="geoReplicatedPrimaryHostName", visibility=["read"] + ) + """The unchanging DNS name which will always point to current geo-primary cache among the linked + redis caches for seamless Geo Failover experience.""" + primary_host_name: Optional[str] = rest_field(name="primaryHostName", visibility=["read"]) + """The changing DNS name that resolves to the current geo-primary cache among the linked redis + caches before or after the Geo Failover.""" + + @overload + def __init__( + self, + *, + linked_redis_cache_id: str, + linked_redis_cache_location: str, + server_role: Union[str, "_models.ReplicationRole"], + ) -> 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 RedisLinkedServerProperties(RedisLinkedServerCreateProperties): + """Properties of a linked server to be returned in get/put response. + + :ivar linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. + :vartype linked_redis_cache_id: str + :ivar linked_redis_cache_location: Location of the linked redis cache. Required. + :vartype linked_redis_cache_location: str + :ivar server_role: Role of the linked server. Required. Known values are: "Primary" and + "Secondary". + :vartype server_role: str or ~azure.mgmt.redis.models.ReplicationRole + :ivar geo_replicated_primary_host_name: The unchanging DNS name which will always point to + current geo-primary cache among the linked redis caches for seamless Geo Failover experience. + :vartype geo_replicated_primary_host_name: str + :ivar primary_host_name: The changing DNS name that resolves to the current geo-primary cache + among the linked redis caches before or after the Geo Failover. + :vartype primary_host_name: str + :ivar provisioning_state: Terminal state of the link between primary and secondary redis cache. + :vartype provisioning_state: str + """ + + provisioning_state: Optional[str] = rest_field(name="provisioningState", visibility=["read"]) + """Terminal state of the link between primary and secondary redis cache.""" + + @overload + def __init__( + self, + *, + linked_redis_cache_id: str, + linked_redis_cache_location: str, + server_role: Union[str, "_models.ReplicationRole"], + ) -> 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 RedisLinkedServerWithProperties(ProxyResource): + """Response to put/get linked server (with properties) for Redis cache. + + :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.redis.models.SystemData + :ivar properties: Properties of the linked server. + :vartype properties: ~azure.mgmt.redis.models.RedisLinkedServerProperties + """ + + properties: Optional["_models.RedisLinkedServerProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Properties of the linked server.""" + + __flattened_items = [ + "linked_redis_cache_id", + "linked_redis_cache_location", + "server_role", + "geo_replicated_primary_host_name", + "primary_host_name", + "provisioning_state", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.RedisLinkedServerProperties"] = 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 RedisPatchSchedule(ProxyResource): + """Response to put/get patch schedules for Redis cache. + + :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.redis.models.SystemData + :ivar properties: List of patch schedules for a Redis cache. Required. + :vartype properties: ~azure.mgmt.redis.models.ScheduleEntries + :ivar location: The geo-location where the resource lives. + :vartype location: str + """ + + properties: "_models.ScheduleEntries" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """List of patch schedules for a Redis cache. Required.""" + location: Optional[str] = rest_field(visibility=["read"]) + """The geo-location where the resource lives.""" + + __flattened_items = ["schedule_entries"] + + @overload + def __init__( + self, + *, + properties: "_models.ScheduleEntries", + ) -> 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 RedisProperties(RedisCreateProperties): + """Properties of the redis cache. + + :ivar redis_configuration: All Redis Settings. Few possible keys: + rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, + maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, + aof-storage-connection-string-1 etc. + :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration + :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is + required) or the value 'latest' which refers to the latest stable Redis version that is + available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. + :vartype redis_version: str + :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. + :vartype enable_non_ssl_port: bool + :ivar replicas_per_master: The number of replicas to be created per primary. + :vartype replicas_per_master: int + :ivar replicas_per_primary: The number of replicas to be created per primary. + :vartype replicas_per_primary: int + :ivar tenant_settings: A dictionary of tenant settings. + :vartype tenant_settings: dict[str, str] + :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. + :vartype shard_count: int + :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or + higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". + :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion + :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private + endpoints are the exclusive access method. Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess + :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your + Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at + least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: + "Stable" and "Preview". + :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel + :ivar disable_access_key_authentication: Authentication to Redis through access keys is + disabled when set as true. Default value is false. + :vartype disable_access_key_authentication: bool + :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the + Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones + based on regional availability and capacity. 'UserDefined' will select availability zones + passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If + 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed + in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' + in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and + "NoZones". + :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy + :ivar sku: The SKU of the Redis cache to deploy. Required. + :vartype sku: ~azure.mgmt.redis.models.Sku + :ivar subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis + cache in. Example format: + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. + :vartype subnet_id: str + :ivar static_ip: Static IP address. Optionally, may be specified when deploying a Redis cache + inside an existing Azure Virtual Network; auto assigned by default. + :vartype static_ip: str + :ivar provisioning_state: Redis instance provisioning status. Known values are: "Creating", + "Deleting", "Disabled", "Failed", "Linking", "Provisioning", "RecoveringScaleFailure", + "Scaling", "Succeeded", "Unlinking", "Unprovisioning", "Updating", "ConfiguringAAD", + "Migrating", "MigrationFailed", "MigrationSucceeded", "MigrationCancelling", and + "MigrationCancellationFailed". + :vartype provisioning_state: str or ~azure.mgmt.redis.models.ProvisioningState + :ivar host_name: Redis host name. + :vartype host_name: str + :ivar port: Redis non-SSL port. + :vartype port: int + :ivar ssl_port: Redis SSL port. + :vartype ssl_port: int + :ivar access_keys: The keys of the Redis cache - not set if this object is not the response to + Create or Update redis cache. + :vartype access_keys: ~azure.mgmt.redis.models.RedisAccessKeys + :ivar linked_servers: List of the linked servers associated with the cache. + :vartype linked_servers: list[~azure.mgmt.redis.models.RedisLinkedServer] + :ivar instances: List of the Redis instances associated with the cache. + :vartype instances: list[~azure.mgmt.redis.models.RedisInstanceDetails] + :ivar private_endpoint_connections: List of private endpoint connection associated with the + specified redis cache. + :vartype private_endpoint_connections: list[~azure.mgmt.redis.models.PrivateEndpointConnection] + :ivar target_amr_resource_id: The resource ID of the target Azure Managed Redis resource that + this Azure Cache for Redis resource is being migrated to. + :vartype target_amr_resource_id: str + """ + + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """Redis instance provisioning status. Known values are: \"Creating\", \"Deleting\", \"Disabled\", + \"Failed\", \"Linking\", \"Provisioning\", \"RecoveringScaleFailure\", \"Scaling\", + \"Succeeded\", \"Unlinking\", \"Unprovisioning\", \"Updating\", \"ConfiguringAAD\", + \"Migrating\", \"MigrationFailed\", \"MigrationSucceeded\", \"MigrationCancelling\", and + \"MigrationCancellationFailed\".""" + host_name: Optional[str] = rest_field(name="hostName", visibility=["read"]) + """Redis host name.""" + port: Optional[int] = rest_field(visibility=["read"]) + """Redis non-SSL port.""" + ssl_port: Optional[int] = rest_field(name="sslPort", visibility=["read"]) + """Redis SSL port.""" + access_keys: Optional["_models.RedisAccessKeys"] = rest_field(name="accessKeys", visibility=["read"]) + """The keys of the Redis cache - not set if this object is not the response to Create or Update + redis cache.""" + linked_servers: Optional[list["_models.RedisLinkedServer"]] = rest_field(name="linkedServers", visibility=["read"]) + """List of the linked servers associated with the cache.""" + instances: Optional[list["_models.RedisInstanceDetails"]] = rest_field(visibility=["read"]) + """List of the Redis instances associated with the cache.""" + private_endpoint_connections: Optional[list["_models.PrivateEndpointConnection"]] = rest_field( + name="privateEndpointConnections", visibility=["read"] + ) + """List of private endpoint connection associated with the specified redis cache.""" + target_amr_resource_id: Optional[str] = rest_field(name="targetAmrResourceId", visibility=["read"]) + """The resource ID of the target Azure Managed Redis resource that this Azure Cache for Redis + resource is being migrated to.""" + + @overload + def __init__( + self, + *, + sku: "_models.Sku", + redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, + redis_version: Optional[str] = None, + enable_non_ssl_port: Optional[bool] = None, + replicas_per_master: Optional[int] = None, + replicas_per_primary: Optional[int] = None, + tenant_settings: Optional[dict[str, str]] = None, + shard_count: Optional[int] = None, + minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, + disable_access_key_authentication: Optional[bool] = None, + zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, + subnet_id: Optional[str] = None, + static_ip: 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 RedisRebootParameters(_Model): + """Specifies which Redis node(s) to reboot. + + :ivar reboot_type: Which Redis node(s) to reboot. Depending on this value data loss is + possible. Known values are: "PrimaryNode", "SecondaryNode", and "AllNodes". + :vartype reboot_type: str or ~azure.mgmt.redis.models.RebootType + :ivar shard_id: If clustering is enabled, the ID of the shard to be rebooted. + :vartype shard_id: int + :ivar ports: A list of redis instances to reboot, specified by per-instance SSL ports or + non-SSL ports. + :vartype ports: list[int] + """ + + reboot_type: Optional[Union[str, "_models.RebootType"]] = rest_field( + name="rebootType", visibility=["read", "create", "update", "delete", "query"] + ) + """Which Redis node(s) to reboot. Depending on this value data loss is possible. Known values are: + \"PrimaryNode\", \"SecondaryNode\", and \"AllNodes\".""" + shard_id: Optional[int] = rest_field(name="shardId", visibility=["read", "create", "update", "delete", "query"]) + """If clustering is enabled, the ID of the shard to be rebooted.""" + ports: Optional[list[int]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A list of redis instances to reboot, specified by per-instance SSL ports or non-SSL ports.""" + + @overload + def __init__( + self, + *, + reboot_type: Optional[Union[str, "_models.RebootType"]] = None, + shard_id: Optional[int] = None, + ports: Optional[list[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 RedisRegenerateKeyParameters(_Model): + """Specifies which Redis access keys to reset. + + :ivar key_type: The Redis access key to regenerate. Required. Known values are: "Primary" and + "Secondary". + :vartype key_type: str or ~azure.mgmt.redis.models.RedisKeyType + """ + + key_type: Union[str, "_models.RedisKeyType"] = rest_field( + name="keyType", visibility=["read", "create", "update", "delete", "query"] + ) + """The Redis access key to regenerate. Required. Known values are: \"Primary\" and \"Secondary\".""" + + @overload + def __init__( + self, + *, + key_type: Union[str, "_models.RedisKeyType"], + ) -> 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 TrackedResource(Resource): + """Tracked 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.redis.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + """ + + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource tags.""" + location: str = rest_field(visibility=["read", "create"]) + """The geo-location where the resource lives. Required.""" + + @overload + def __init__( + self, + *, + location: str, + tags: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RedisResource(TrackedResource): + """A single Redis item in List or Get Operation. + + :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.redis.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar properties: Redis cache properties. Required. + :vartype properties: ~azure.mgmt.redis.models.RedisProperties + :ivar zones: The availability zones. + :vartype zones: list[str] + :ivar identity: The managed service identities assigned to this resource. + :vartype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity + """ + + properties: "_models.RedisProperties" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Redis cache properties. Required.""" + zones: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The availability zones.""" + identity: Optional["_models.ManagedServiceIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The managed service identities assigned to this resource.""" + + __flattened_items = [ + "redis_configuration", + "redis_version", + "enable_non_ssl_port", + "replicas_per_master", + "replicas_per_primary", + "tenant_settings", + "shard_count", + "minimum_tls_version", + "public_network_access", + "update_channel", + "disable_access_key_authentication", + "zonal_allocation_policy", + "sku", + "subnet_id", + "static_ip", + "provisioning_state", + "host_name", + "port", + "ssl_port", + "access_keys", + "linked_servers", + "instances", + "private_endpoint_connections", + "target_amr_resource_id", + ] + + @overload + def __init__( + self, + *, + location: str, + properties: "_models.RedisProperties", + tags: Optional[dict[str, str]] = None, + zones: Optional[list[str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = 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 RedisUpdateParameters(_Model): + """Parameters supplied to the Update Redis operation. + + :ivar properties: Redis cache properties. + :vartype properties: ~azure.mgmt.redis.models.RedisUpdateProperties + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar identity: The identity of the resource. + :vartype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity + """ + + properties: Optional["_models.RedisUpdateProperties"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Redis cache properties.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Resource tags.""" + identity: Optional["_models.ManagedServiceIdentity"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The identity of the resource.""" + + __flattened_items = [ + "redis_configuration", + "redis_version", + "enable_non_ssl_port", + "replicas_per_master", + "replicas_per_primary", + "tenant_settings", + "shard_count", + "minimum_tls_version", + "public_network_access", + "update_channel", + "disable_access_key_authentication", + "zonal_allocation_policy", + "sku", + ] + + @overload + def __init__( + self, + *, + properties: Optional["_models.RedisUpdateProperties"] = None, + tags: Optional[dict[str, str]] = None, + identity: Optional["_models.ManagedServiceIdentity"] = 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 RedisUpdateProperties(RedisCommonProperties): + """Patchable properties of the redis cache. + + :ivar redis_configuration: All Redis Settings. Few possible keys: + rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, + maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, + aof-storage-connection-string-1 etc. + :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration + :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is + required) or the value 'latest' which refers to the latest stable Redis version that is + available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. + :vartype redis_version: str + :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. + :vartype enable_non_ssl_port: bool + :ivar replicas_per_master: The number of replicas to be created per primary. + :vartype replicas_per_master: int + :ivar replicas_per_primary: The number of replicas to be created per primary. + :vartype replicas_per_primary: int + :ivar tenant_settings: A dictionary of tenant settings. + :vartype tenant_settings: dict[str, str] + :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. + :vartype shard_count: int + :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or + higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". + :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion + :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. + Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private + endpoints are the exclusive access method. Known values are: "Enabled" and "Disabled". + :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess + :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your + Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at + least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: + "Stable" and "Preview". + :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel + :ivar disable_access_key_authentication: Authentication to Redis through access keys is + disabled when set as true. Default value is false. + :vartype disable_access_key_authentication: bool + :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the + Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones + based on regional availability and capacity. 'UserDefined' will select availability zones + passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If + 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed + in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' + in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and + "NoZones". + :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy + :ivar sku: The SKU of the Redis cache to deploy. + :vartype sku: ~azure.mgmt.redis.models.Sku + """ + + sku: Optional["_models.Sku"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The SKU of the Redis cache to deploy.""" + + @overload + def __init__( + self, + *, + redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, + redis_version: Optional[str] = None, + enable_non_ssl_port: Optional[bool] = None, + replicas_per_master: Optional[int] = None, + replicas_per_primary: Optional[int] = None, + tenant_settings: Optional[dict[str, str]] = None, + shard_count: Optional[int] = None, + minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, + public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, + update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, + disable_access_key_authentication: Optional[bool] = None, + zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, + sku: Optional["_models.Sku"] = 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 ScheduleEntries(_Model): + """List of patch schedules for a Redis cache. + + :ivar schedule_entries: List of patch schedules for a Redis cache. Required. + :vartype schedule_entries: list[~azure.mgmt.redis.models.ScheduleEntry] + """ + + schedule_entries: list["_models.ScheduleEntry"] = rest_field( + name="scheduleEntries", visibility=["read", "create", "update", "delete", "query"] + ) + """List of patch schedules for a Redis cache. Required.""" + + @overload + def __init__( + self, + *, + schedule_entries: list["_models.ScheduleEntry"], + ) -> 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 ScheduleEntry(_Model): + """Patch schedule entry for a Premium Redis Cache. + + :ivar day_of_week: Day of the week when a cache can be patched. Required. Known values are: + "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Everyday", and + "Weekend". + :vartype day_of_week: str or ~azure.mgmt.redis.models.DayOfWeek + :ivar start_hour_utc: Start hour after which cache patching can start. Required. + :vartype start_hour_utc: int + :ivar maintenance_window: ISO8601 timespan specifying how much time cache patching can take. + :vartype maintenance_window: ~datetime.timedelta + """ + + day_of_week: Union[str, "_models.DayOfWeek"] = rest_field( + name="dayOfWeek", visibility=["read", "create", "update", "delete", "query"] + ) + """Day of the week when a cache can be patched. Required. Known values are: \"Monday\", + \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\", \"Everyday\", + and \"Weekend\".""" + start_hour_utc: int = rest_field(name="startHourUtc", visibility=["read", "create", "update", "delete", "query"]) + """Start hour after which cache patching can start. Required.""" + maintenance_window: Optional[datetime.timedelta] = rest_field( + name="maintenanceWindow", visibility=["read", "create", "update", "delete", "query"] + ) + """ISO8601 timespan specifying how much time cache patching can take.""" + + @overload + def __init__( + self, + *, + day_of_week: Union[str, "_models.DayOfWeek"], + start_hour_utc: int, + maintenance_window: Optional[datetime.timedelta] = 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 Sku(_Model): + """SKU parameters supplied to the create Redis operation. + + :ivar name: The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium). + Required. Known values are: "Basic", "Standard", and "Premium". + :vartype name: str or ~azure.mgmt.redis.models.SkuName + :ivar family: The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium). + Required. Known values are: "C" and "P". + :vartype family: str or ~azure.mgmt.redis.models.SkuFamily + :ivar capacity: The size of the Redis cache to deploy. Valid values: for C (Basic/Standard) + family (0, 1, 2, 3, 4, 5, 6), for P (Premium) family (1, 2, 3, 4). Required. + :vartype capacity: int + """ + + name: Union[str, "_models.SkuName"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium). Required. Known + values are: \"Basic\", \"Standard\", and \"Premium\".""" + family: Union[str, "_models.SkuFamily"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium). Required. Known + values are: \"C\" and \"P\".""" + capacity: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The size of the Redis cache to deploy. Valid values: for C (Basic/Standard) family (0, 1, 2, 3, + 4, 5, 6), for P (Premium) family (1, 2, 3, 4). Required.""" + + @overload + def __init__( + self, + *, + name: Union[str, "_models.SkuName"], + family: Union[str, "_models.SkuFamily"], + capacity: int, + ) -> 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.redis.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.redis.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read", "create", "update", "delete", "query"]) + """The identity that created the resource.""" + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="createdByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that created the resource. Known values are: \"User\", \"Application\", + \"ManagedIdentity\", and \"Key\".""" + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource creation (UTC).""" + last_modified_by: Optional[str] = rest_field( + name="lastModifiedBy", visibility=["read", "create", "update", "delete", "query"] + ) + """The identity that last modified the resource.""" + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = rest_field( + name="lastModifiedByType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of identity that last modified the resource. Known values are: \"User\", + \"Application\", \"ManagedIdentity\", and \"Key\".""" + last_modified_at: Optional[datetime.datetime] = rest_field( + name="lastModifiedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The timestamp of resource last modification (UTC).""" + + @overload + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UpgradeNotification(_Model): + """Properties of upgrade notification. + + :ivar name: Name of upgrade notification. + :vartype name: str + :ivar timestamp: Timestamp when upgrade notification occurred. + :vartype timestamp: ~datetime.datetime + :ivar upsell_notification: Details about this upgrade notification. + :vartype upsell_notification: dict[str, str] + """ + + name: Optional[str] = rest_field(visibility=["read"]) + """Name of upgrade notification.""" + timestamp: Optional[datetime.datetime] = rest_field(visibility=["read"], format="rfc3339") + """Timestamp when upgrade notification occurred.""" + upsell_notification: Optional[dict[str, str]] = rest_field(name="upsellNotification", visibility=["read"]) + """Details about this upgrade notification.""" + + +class UserAssignedIdentity(_Model): + """User assigned identity properties. + + :ivar principal_id: The principal ID of the assigned identity. + :vartype principal_id: str + :ivar client_id: The client ID of the assigned identity. + :vartype client_id: str + """ + + principal_id: Optional[str] = rest_field(name="principalId", visibility=["read"]) + """The principal ID of the assigned identity.""" + client_id: Optional[str] = rest_field(name="clientId", visibility=["read"]) + """The client ID of the assigned identity.""" diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_models_py3.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_models_py3.py deleted file mode 100644 index 5376570520ec..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_models_py3.py +++ /dev/null @@ -1,3554 +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 datetime -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union - -from .. import _serialization - -if TYPE_CHECKING: - from .. import models as _models - - -class CheckNameAvailabilityParameters(_serialization.Model): - """Parameters body to pass for resource name availability check. - - All required parameters must be populated in order to send to server. - - :ivar name: Resource name. Required. - :vartype name: str - :ivar type: Resource type. The only legal value of this property for checking redis cache name - availability is 'Microsoft.Cache/redis'. Required. - :vartype type: str - """ - - _validation = { - "name": {"required": True}, - "type": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, *, name: str, type: str, **kwargs: Any) -> None: - """ - :keyword name: Resource name. Required. - :paramtype name: str - :keyword type: Resource type. The only legal value of this property for checking redis cache - name availability is 'Microsoft.Cache/redis'. Required. - :paramtype type: str - """ - super().__init__(**kwargs) - self.name = name - self.type = type - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - 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 - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.redis.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.redis.models.ErrorAdditionalInfo] - """ - - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - - _attribute_map = { - "code": {"key": "code", "type": "str"}, - "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed - operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.mgmt.redis.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: - """ - :keyword error: The error object. - :paramtype error: ~azure.mgmt.redis.models.ErrorDetail - """ - super().__init__(**kwargs) - self.error = error - - -class ExportRDBParameters(_serialization.Model): - """Parameters for Redis export operation. - - All required parameters must be populated in order to send to server. - - :ivar format: File format. - :vartype format: str - :ivar prefix: Prefix to use for exported files. Required. - :vartype prefix: str - :ivar container: Container name to export to. Required. - :vartype container: str - :ivar preferred_data_archive_auth_method: Preferred auth method to communicate to storage - account used for data archive, specify SAS or ManagedIdentity, default value is SAS. - :vartype preferred_data_archive_auth_method: str - :ivar storage_subscription_id: Subscription id of the storage container for data to be exported - using ManagedIdentity. - :vartype storage_subscription_id: str - """ - - _validation = { - "prefix": {"required": True}, - "container": {"required": True}, - } - - _attribute_map = { - "format": {"key": "format", "type": "str"}, - "prefix": {"key": "prefix", "type": "str"}, - "container": {"key": "container", "type": "str"}, - "preferred_data_archive_auth_method": {"key": "preferred-data-archive-auth-method", "type": "str"}, - "storage_subscription_id": {"key": "storage-subscription-id", "type": "str"}, - } - - def __init__( - self, - *, - prefix: str, - container: str, - format: Optional[str] = None, - preferred_data_archive_auth_method: Optional[str] = None, - storage_subscription_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword format: File format. - :paramtype format: str - :keyword prefix: Prefix to use for exported files. Required. - :paramtype prefix: str - :keyword container: Container name to export to. Required. - :paramtype container: str - :keyword preferred_data_archive_auth_method: Preferred auth method to communicate to storage - account used for data archive, specify SAS or ManagedIdentity, default value is SAS. - :paramtype preferred_data_archive_auth_method: str - :keyword storage_subscription_id: Subscription id of the storage container for data to be - exported using ManagedIdentity. - :paramtype storage_subscription_id: str - """ - super().__init__(**kwargs) - self.format = format - self.prefix = prefix - self.container = container - self.preferred_data_archive_auth_method = preferred_data_archive_auth_method - self.storage_subscription_id = storage_subscription_id - - -class ImportRDBParameters(_serialization.Model): - """Parameters for Redis import operation. - - All required parameters must be populated in order to send to server. - - :ivar format: File format. - :vartype format: str - :ivar files: files to import. Required. - :vartype files: list[str] - :ivar preferred_data_archive_auth_method: Preferred auth method to communicate to storage - account used for data archive, specify SAS or ManagedIdentity, default value is SAS. - :vartype preferred_data_archive_auth_method: str - :ivar storage_subscription_id: Subscription id of the storage container containing files to - import using Managed Identity. - :vartype storage_subscription_id: str - """ - - _validation = { - "files": {"required": True}, - } - - _attribute_map = { - "format": {"key": "format", "type": "str"}, - "files": {"key": "files", "type": "[str]"}, - "preferred_data_archive_auth_method": {"key": "preferred-data-archive-auth-method", "type": "str"}, - "storage_subscription_id": {"key": "storage-subscription-id", "type": "str"}, - } - - def __init__( - self, - *, - files: List[str], - format: Optional[str] = None, - preferred_data_archive_auth_method: Optional[str] = None, - storage_subscription_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword format: File format. - :paramtype format: str - :keyword files: files to import. Required. - :paramtype files: list[str] - :keyword preferred_data_archive_auth_method: Preferred auth method to communicate to storage - account used for data archive, specify SAS or ManagedIdentity, default value is SAS. - :paramtype preferred_data_archive_auth_method: str - :keyword storage_subscription_id: Subscription id of the storage container containing files to - import using Managed Identity. - :paramtype storage_subscription_id: str - """ - super().__init__(**kwargs) - self.format = format - self.files = files - self.preferred_data_archive_auth_method = preferred_data_archive_auth_method - self.storage_subscription_id = storage_subscription_id - - -class ManagedServiceIdentity(_serialization.Model): - """Managed service identity (system assigned and/or user assigned identities). - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar principal_id: The service principal ID of the system assigned identity. This property - will only be provided for a system assigned identity. - :vartype principal_id: str - :ivar tenant_id: The tenant ID of the system assigned identity. This property will only be - provided for a system assigned identity. - :vartype tenant_id: str - :ivar type: Type of managed service identity (where both SystemAssigned and UserAssigned types - are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", and - "SystemAssigned, UserAssigned". - :vartype type: str or ~azure.mgmt.redis.models.ManagedServiceIdentityType - :ivar user_assigned_identities: The set of user assigned identities associated with the - resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long - The dictionary values can be empty objects ({}) in requests. - :vartype user_assigned_identities: dict[str, ~azure.mgmt.redis.models.UserAssignedIdentity] - """ - - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - "type": {"required": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, - } - - def __init__( - self, - *, - type: Union[str, "_models.ManagedServiceIdentityType"], - user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: Type of managed service identity (where both SystemAssigned and UserAssigned - types are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", and - "SystemAssigned, UserAssigned". - :paramtype type: str or ~azure.mgmt.redis.models.ManagedServiceIdentityType - :keyword user_assigned_identities: The set of user assigned identities associated with the - resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long - The dictionary values can be empty objects ({}) in requests. - :paramtype user_assigned_identities: dict[str, ~azure.mgmt.redis.models.UserAssignedIdentity] - """ - super().__init__(**kwargs) - self.principal_id = None - self.tenant_id = None - self.type = type - self.user_assigned_identities = user_assigned_identities - - -class NotificationListResponse(_serialization.Model): - """The response of listUpgradeNotifications. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of all notifications. - :vartype value: list[~azure.mgmt.redis.models.UpgradeNotification] - :ivar next_link: Link for next set of notifications. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[UpgradeNotification]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[List["_models.UpgradeNotification"]] = None, **kwargs: Any) -> None: - """ - :keyword value: List of all notifications. - :paramtype value: list[~azure.mgmt.redis.models.UpgradeNotification] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class Operation(_serialization.Model): - """REST API operation. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar display: The object that describes the operation. - :vartype display: ~azure.mgmt.redis.models.OperationDisplay - """ - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplay"}, - } - - def __init__( - self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any - ) -> None: - """ - :keyword name: Operation name: {provider}/{resource}/{operation}. - :paramtype name: str - :keyword display: The object that describes the operation. - :paramtype display: ~azure.mgmt.redis.models.OperationDisplay - """ - super().__init__(**kwargs) - self.name = name - self.display = display - - -class OperationDisplay(_serialization.Model): - """The object that describes the operation. - - :ivar provider: Friendly name of the resource provider. - :vartype provider: str - :ivar operation: Operation type: read, write, delete, listKeys/action, etc. - :vartype operation: str - :ivar resource: Resource type on which the operation is performed. - :vartype resource: str - :ivar description: Friendly name of the operation. - :vartype description: str - """ - - _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__( - self, - *, - provider: Optional[str] = None, - operation: Optional[str] = None, - resource: Optional[str] = None, - description: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword provider: Friendly name of the resource provider. - :paramtype provider: str - :keyword operation: Operation type: read, write, delete, listKeys/action, etc. - :paramtype operation: str - :keyword resource: Resource type on which the operation is performed. - :paramtype resource: str - :keyword description: Friendly name of the operation. - :paramtype description: str - """ - super().__init__(**kwargs) - self.provider = provider - self.operation = operation - self.resource = resource - self.description = description - - -class OperationListResult(_serialization.Model): - """Result of the request to list REST API operations. It contains a list of operations and a URL - nextLink to get the next set of results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of operations supported by the resource provider. - :vartype value: list[~azure.mgmt.redis.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[Operation]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[List["_models.Operation"]] = None, **kwargs: Any) -> None: - """ - :keyword value: List of operations supported by the resource provider. - :paramtype value: list[~azure.mgmt.redis.models.Operation] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class OperationStatusResult(_serialization.Model): - """The current status of an async operation. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified ID for the async operation. - :vartype id: str - :ivar name: Name of the async operation. - :vartype name: str - :ivar status: Operation status. Required. - :vartype status: str - :ivar percent_complete: Percent of the operation that is complete. - :vartype percent_complete: float - :ivar start_time: The start time of the operation. - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time of the operation. - :vartype end_time: ~datetime.datetime - :ivar operations: The operations list. - :vartype operations: list[~azure.mgmt.redis.models.OperationStatusResult] - :ivar error: If present, details of the operation error. - :vartype error: ~azure.mgmt.redis.models.ErrorDetail - """ - - _validation = { - "status": {"required": True}, - "percent_complete": {"maximum": 100, "minimum": 0}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "percent_complete": {"key": "percentComplete", "type": "float"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "operations": {"key": "operations", "type": "[OperationStatusResult]"}, - "error": {"key": "error", "type": "ErrorDetail"}, - } - - def __init__( - self, - *, - status: str, - id: Optional[str] = None, # pylint: disable=redefined-builtin - name: Optional[str] = None, - percent_complete: Optional[float] = None, - start_time: Optional[datetime.datetime] = None, - end_time: Optional[datetime.datetime] = None, - operations: Optional[List["_models.OperationStatusResult"]] = None, - error: Optional["_models.ErrorDetail"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Fully qualified ID for the async operation. - :paramtype id: str - :keyword name: Name of the async operation. - :paramtype name: str - :keyword status: Operation status. Required. - :paramtype status: str - :keyword percent_complete: Percent of the operation that is complete. - :paramtype percent_complete: float - :keyword start_time: The start time of the operation. - :paramtype start_time: ~datetime.datetime - :keyword end_time: The end time of the operation. - :paramtype end_time: ~datetime.datetime - :keyword operations: The operations list. - :paramtype operations: list[~azure.mgmt.redis.models.OperationStatusResult] - :keyword error: If present, details of the operation error. - :paramtype error: ~azure.mgmt.redis.models.ErrorDetail - """ - super().__init__(**kwargs) - self.id = id - self.name = name - self.status = status - self.percent_complete = percent_complete - self.start_time = start_time - self.end_time = end_time - self.operations = operations - self.error = error - - -class OperationStatus(OperationStatusResult): - """Asynchronous operation status. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified ID for the async operation. - :vartype id: str - :ivar name: Name of the async operation. - :vartype name: str - :ivar status: Operation status. Required. - :vartype status: str - :ivar percent_complete: Percent of the operation that is complete. - :vartype percent_complete: float - :ivar start_time: The start time of the operation. - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time of the operation. - :vartype end_time: ~datetime.datetime - :ivar operations: The operations list. - :vartype operations: list[~azure.mgmt.redis.models.OperationStatusResult] - :ivar error: If present, details of the operation error. - :vartype error: ~azure.mgmt.redis.models.ErrorDetail - :ivar properties: Additional properties from RP, only when operation is successful. - :vartype properties: dict[str, any] - """ - - _validation = { - "status": {"required": True}, - "percent_complete": {"maximum": 100, "minimum": 0}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "percent_complete": {"key": "percentComplete", "type": "float"}, - "start_time": {"key": "startTime", "type": "iso-8601"}, - "end_time": {"key": "endTime", "type": "iso-8601"}, - "operations": {"key": "operations", "type": "[OperationStatusResult]"}, - "error": {"key": "error", "type": "ErrorDetail"}, - "properties": {"key": "properties", "type": "{object}"}, - } - - def __init__( - self, - *, - status: str, - id: Optional[str] = None, # pylint: disable=redefined-builtin - name: Optional[str] = None, - percent_complete: Optional[float] = None, - start_time: Optional[datetime.datetime] = None, - end_time: Optional[datetime.datetime] = None, - operations: Optional[List["_models.OperationStatusResult"]] = None, - error: Optional["_models.ErrorDetail"] = None, - properties: Optional[Dict[str, Any]] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: Fully qualified ID for the async operation. - :paramtype id: str - :keyword name: Name of the async operation. - :paramtype name: str - :keyword status: Operation status. Required. - :paramtype status: str - :keyword percent_complete: Percent of the operation that is complete. - :paramtype percent_complete: float - :keyword start_time: The start time of the operation. - :paramtype start_time: ~datetime.datetime - :keyword end_time: The end time of the operation. - :paramtype end_time: ~datetime.datetime - :keyword operations: The operations list. - :paramtype operations: list[~azure.mgmt.redis.models.OperationStatusResult] - :keyword error: If present, details of the operation error. - :paramtype error: ~azure.mgmt.redis.models.ErrorDetail - :keyword properties: Additional properties from RP, only when operation is successful. - :paramtype properties: dict[str, any] - """ - super().__init__( - id=id, - name=name, - status=status, - percent_complete=percent_complete, - start_time=start_time, - end_time=end_time, - operations=operations, - error=error, - **kwargs - ) - self.properties = properties - - -class PrivateEndpoint(_serialization.Model): - """The Private Endpoint resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ARM identifier for Private Endpoint. - :vartype id: str - """ - - _validation = { - "id": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - - -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. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 - """ - - _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"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class PrivateEndpointConnection(Resource): - """The Private Endpoint Connection resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 private_endpoint: The resource of private end point. - :vartype private_endpoint: ~azure.mgmt.redis.models.PrivateEndpoint - :ivar private_link_service_connection_state: A collection of information about the state of the - connection between service consumer and provider. - :vartype private_link_service_connection_state: - ~azure.mgmt.redis.models.PrivateLinkServiceConnectionState - :ivar provisioning_state: The provisioning state of the private endpoint connection resource. - Known values are: "Succeeded", "Creating", "Deleting", and "Failed". - :vartype provisioning_state: str or - ~azure.mgmt.redis.models.PrivateEndpointConnectionProvisioningState - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpoint"}, - "private_link_service_connection_state": { - "key": "properties.privateLinkServiceConnectionState", - "type": "PrivateLinkServiceConnectionState", - }, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - private_endpoint: Optional["_models.PrivateEndpoint"] = None, - private_link_service_connection_state: Optional["_models.PrivateLinkServiceConnectionState"] = None, - **kwargs: Any - ) -> None: - """ - :keyword private_endpoint: The resource of private end point. - :paramtype private_endpoint: ~azure.mgmt.redis.models.PrivateEndpoint - :keyword private_link_service_connection_state: A collection of information about the state of - the connection between service consumer and provider. - :paramtype private_link_service_connection_state: - ~azure.mgmt.redis.models.PrivateLinkServiceConnectionState - """ - super().__init__(**kwargs) - self.private_endpoint = private_endpoint - self.private_link_service_connection_state = private_link_service_connection_state - self.provisioning_state = None - - -class PrivateEndpointConnectionListResult(_serialization.Model): - """List of private endpoint connection associated with the specified storage account. - - :ivar value: Array of private endpoint connections. - :vartype value: list[~azure.mgmt.redis.models.PrivateEndpointConnection] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, - } - - def __init__(self, *, value: Optional[List["_models.PrivateEndpointConnection"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Array of private endpoint connections. - :paramtype value: list[~azure.mgmt.redis.models.PrivateEndpointConnection] - """ - super().__init__(**kwargs) - self.value = value - - -class PrivateLinkResource(Resource): - """A private link resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 group_id: The private link resource group id. - :vartype group_id: str - :ivar required_members: The private link resource required member names. - :vartype required_members: list[str] - :ivar required_zone_names: The private link resource Private link DNS zone name. - :vartype required_zone_names: list[str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "group_id": {"readonly": True}, - "required_members": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "group_id": {"key": "properties.groupId", "type": "str"}, - "required_members": {"key": "properties.requiredMembers", "type": "[str]"}, - "required_zone_names": {"key": "properties.requiredZoneNames", "type": "[str]"}, - } - - def __init__(self, *, required_zone_names: Optional[List[str]] = None, **kwargs: Any) -> None: - """ - :keyword required_zone_names: The private link resource Private link DNS zone name. - :paramtype required_zone_names: list[str] - """ - super().__init__(**kwargs) - self.group_id = None - self.required_members = None - self.required_zone_names = required_zone_names - - -class PrivateLinkResourceListResult(_serialization.Model): - """A list of private link resources. - - :ivar value: Array of private link resources. - :vartype value: list[~azure.mgmt.redis.models.PrivateLinkResource] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateLinkResource]"}, - } - - def __init__(self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Array of private link resources. - :paramtype value: list[~azure.mgmt.redis.models.PrivateLinkResource] - """ - super().__init__(**kwargs) - self.value = value - - -class PrivateLinkServiceConnectionState(_serialization.Model): - """A collection of information about the state of the connection between service consumer and - provider. - - :ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner - of the service. Known values are: "Pending", "Approved", and "Rejected". - :vartype status: str or ~azure.mgmt.redis.models.PrivateEndpointServiceConnectionStatus - :ivar description: The reason for approval/rejection of the connection. - :vartype description: str - :ivar actions_required: A message indicating if changes on the service provider require any - updates on the consumer. - :vartype actions_required: str - """ - - _attribute_map = { - "status": {"key": "status", "type": "str"}, - "description": {"key": "description", "type": "str"}, - "actions_required": {"key": "actionsRequired", "type": "str"}, - } - - def __init__( - self, - *, - status: Optional[Union[str, "_models.PrivateEndpointServiceConnectionStatus"]] = None, - description: Optional[str] = None, - actions_required: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword status: Indicates whether the connection has been Approved/Rejected/Removed by the - owner of the service. Known values are: "Pending", "Approved", and "Rejected". - :paramtype status: str or ~azure.mgmt.redis.models.PrivateEndpointServiceConnectionStatus - :keyword description: The reason for approval/rejection of the connection. - :paramtype description: str - :keyword actions_required: A message indicating if changes on the service provider require any - updates on the consumer. - :paramtype actions_required: str - """ - super().__init__(**kwargs) - self.status = status - self.description = description - self.actions_required = actions_required - - -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. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 - """ - - -class RedisAccessKeys(_serialization.Model): - """Redis cache access keys. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar primary_key: The current primary key that clients can use to authenticate with Redis - cache. - :vartype primary_key: str - :ivar secondary_key: The current secondary key that clients can use to authenticate with Redis - cache. - :vartype secondary_key: str - """ - - _validation = { - "primary_key": {"readonly": True}, - "secondary_key": {"readonly": True}, - } - - _attribute_map = { - "primary_key": {"key": "primaryKey", "type": "str"}, - "secondary_key": {"key": "secondaryKey", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.primary_key = None - self.secondary_key = None - - -class RedisCacheAccessPolicy(ProxyResource): - """Response to get/put access policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 provisioning_state: Provisioning state of access policy. Known values are: "Updating", - "Succeeded", "Deleting", "Deleted", "Canceled", and "Failed". - :vartype provisioning_state: str or ~azure.mgmt.redis.models.AccessPolicyProvisioningState - :ivar type_properties_type: Built-In or Custom access policy. Known values are: "Custom" and - "BuiltIn". - :vartype type_properties_type: str or ~azure.mgmt.redis.models.AccessPolicyType - :ivar permissions: Permissions for the access policy. Learn how to configure permissions at - https://aka.ms/redis/AADPreRequisites. - :vartype permissions: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "provisioning_state": {"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"}, - "type_properties_type": {"key": "properties.type", "type": "str"}, - "permissions": {"key": "properties.permissions", "type": "str"}, - } - - def __init__(self, *, permissions: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword permissions: Permissions for the access policy. Learn how to configure permissions at - https://aka.ms/redis/AADPreRequisites. - :paramtype permissions: str - """ - super().__init__(**kwargs) - self.provisioning_state = None - self.type_properties_type = None - self.permissions = permissions - - -class RedisCacheAccessPolicyAssignment(ProxyResource): - """Response to an operation on access policy assignment. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 provisioning_state: Provisioning state of an access policy assignment set. Known values - are: "Updating", "Succeeded", "Deleting", "Deleted", "Canceled", and "Failed". - :vartype provisioning_state: str or - ~azure.mgmt.redis.models.AccessPolicyAssignmentProvisioningState - :ivar object_id: Object Id to assign access policy to. - :vartype object_id: str - :ivar object_id_alias: User friendly name for object id. Also represents username for token - based authentication. - :vartype object_id_alias: str - :ivar access_policy_name: The name of the access policy that is being assigned. - :vartype access_policy_name: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "access_policy_name": {"pattern": r"^([a-zA-Z0-9][a-zA-Z0-9- ]*[a-zA-Z0-9]|[a-zA-Z0-9])$"}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "object_id": {"key": "properties.objectId", "type": "str"}, - "object_id_alias": {"key": "properties.objectIdAlias", "type": "str"}, - "access_policy_name": {"key": "properties.accessPolicyName", "type": "str"}, - } - - def __init__( - self, - *, - object_id: Optional[str] = None, - object_id_alias: Optional[str] = None, - access_policy_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword object_id: Object Id to assign access policy to. - :paramtype object_id: str - :keyword object_id_alias: User friendly name for object id. Also represents username for token - based authentication. - :paramtype object_id_alias: str - :keyword access_policy_name: The name of the access policy that is being assigned. - :paramtype access_policy_name: str - """ - super().__init__(**kwargs) - self.provisioning_state = None - self.object_id = object_id - self.object_id_alias = object_id_alias - self.access_policy_name = access_policy_name - - -class RedisCacheAccessPolicyAssignmentList(_serialization.Model): - """List of access policies assignments (with properties) of a Redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of access policies assignments (with properties) of a Redis cache. - :vartype value: list[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :ivar next_link: Link for next set. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RedisCacheAccessPolicyAssignment]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[List["_models.RedisCacheAccessPolicyAssignment"]] = None, **kwargs: Any - ) -> None: - """ - :keyword value: List of access policies assignments (with properties) of a Redis cache. - :paramtype value: list[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class RedisCacheAccessPolicyList(_serialization.Model): - """List of access policies (with properties) of a Redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of access policies (with properties) of a Redis cache. - :vartype value: list[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :ivar next_link: Link for next set. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RedisCacheAccessPolicy]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[List["_models.RedisCacheAccessPolicy"]] = None, **kwargs: Any) -> None: - """ - :keyword value: List of access policies (with properties) of a Redis cache. - :paramtype value: list[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class RedisCommonProperties(_serialization.Model): - """Create/Update/Get common properties of the redis cache. - - :ivar redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is - required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :vartype redis_version: str - :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. - :vartype enable_non_ssl_port: bool - :ivar replicas_per_master: The number of replicas to be created per primary. - :vartype replicas_per_master: int - :ivar replicas_per_primary: The number of replicas to be created per primary. - :vartype replicas_per_primary: int - :ivar tenant_settings: A dictionary of tenant settings. - :vartype tenant_settings: dict[str, str] - :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. - :vartype shard_count: int - :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. - Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private - endpoints are the exclusive access method. Default value is 'Enabled'. Known values are: - "Enabled" and "Disabled". - :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your - Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at - least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :ivar disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :vartype disable_access_key_authentication: bool - :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the - Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - """ - - _attribute_map = { - "redis_configuration": {"key": "redisConfiguration", "type": "RedisCommonPropertiesRedisConfiguration"}, - "redis_version": {"key": "redisVersion", "type": "str"}, - "enable_non_ssl_port": {"key": "enableNonSslPort", "type": "bool"}, - "replicas_per_master": {"key": "replicasPerMaster", "type": "int"}, - "replicas_per_primary": {"key": "replicasPerPrimary", "type": "int"}, - "tenant_settings": {"key": "tenantSettings", "type": "{str}"}, - "shard_count": {"key": "shardCount", "type": "int"}, - "minimum_tls_version": {"key": "minimumTlsVersion", "type": "str"}, - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - "update_channel": {"key": "updateChannel", "type": "str"}, - "disable_access_key_authentication": {"key": "disableAccessKeyAuthentication", "type": "bool"}, - "zonal_allocation_policy": {"key": "zonalAllocationPolicy", "type": "str"}, - } - - def __init__( - self, - *, - redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, - redis_version: Optional[str] = None, - enable_non_ssl_port: bool = False, - replicas_per_master: Optional[int] = None, - replicas_per_primary: Optional[int] = None, - tenant_settings: Optional[Dict[str, str]] = None, - shard_count: Optional[int] = None, - minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, - public_network_access: Union[str, "_models.PublicNetworkAccess"] = "Enabled", - update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, - disable_access_key_authentication: bool = False, - zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :paramtype redis_configuration: - ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :keyword redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' - is required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :paramtype redis_version: str - :keyword enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is - enabled. - :paramtype enable_non_ssl_port: bool - :keyword replicas_per_master: The number of replicas to be created per primary. - :paramtype replicas_per_master: int - :keyword replicas_per_primary: The number of replicas to be created per primary. - :paramtype replicas_per_primary: int - :keyword tenant_settings: A dictionary of tenant settings. - :paramtype tenant_settings: dict[str, str] - :keyword shard_count: The number of shards to be created on a Premium Cluster Cache. - :paramtype shard_count: int - :keyword minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :paramtype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :keyword public_network_access: Whether or not public endpoint access is allowed for this - cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', - private endpoints are the exclusive access method. Default value is 'Enabled'. Known values - are: "Enabled" and "Disabled". - :paramtype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :keyword update_channel: Optional: Specifies the update channel for the monthly Redis updates - your Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates - at least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :paramtype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :keyword disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :paramtype disable_access_key_authentication: bool - :keyword zonal_allocation_policy: Optional: Specifies how availability zones are allocated to - the Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :paramtype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - """ - super().__init__(**kwargs) - self.redis_configuration = redis_configuration - self.redis_version = redis_version - self.enable_non_ssl_port = enable_non_ssl_port - self.replicas_per_master = replicas_per_master - self.replicas_per_primary = replicas_per_primary - self.tenant_settings = tenant_settings - self.shard_count = shard_count - self.minimum_tls_version = minimum_tls_version - self.public_network_access = public_network_access - self.update_channel = update_channel - self.disable_access_key_authentication = disable_access_key_authentication - self.zonal_allocation_policy = zonal_allocation_policy - - -class RedisCommonPropertiesRedisConfiguration(_serialization.Model): - """All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar rdb_backup_enabled: Specifies whether the rdb backup is enabled. - :vartype rdb_backup_enabled: str - :ivar rdb_backup_frequency: Specifies the frequency for creating rdb backup in minutes. Valid - values: (15, 30, 60, 360, 720, 1440). - :vartype rdb_backup_frequency: str - :ivar rdb_backup_max_snapshot_count: Specifies the maximum number of snapshots for rdb backup. - :vartype rdb_backup_max_snapshot_count: str - :ivar rdb_storage_connection_string: The storage account connection string for storing rdb - file. - :vartype rdb_storage_connection_string: str - :ivar aof_backup_enabled: Specifies whether the aof backup is enabled. - :vartype aof_backup_enabled: str - :ivar aof_storage_connection_string0: First storage account connection string. - :vartype aof_storage_connection_string0: str - :ivar aof_storage_connection_string1: Second storage account connection string. - :vartype aof_storage_connection_string1: str - :ivar maxfragmentationmemory_reserved: Value in megabytes reserved for fragmentation per shard. - :vartype maxfragmentationmemory_reserved: str - :ivar maxmemory_policy: The eviction strategy used when your data won't fit within its memory - limit. - :vartype maxmemory_policy: str - :ivar maxmemory_reserved: Value in megabytes reserved for non-cache usage per shard e.g. - failover. - :vartype maxmemory_reserved: str - :ivar maxmemory_delta: Value in megabytes reserved for non-cache usage per shard e.g. failover. - :vartype maxmemory_delta: str - :ivar maxclients: The max clients config. - :vartype maxclients: str - :ivar notify_keyspace_events: The keyspace events which should be monitored. - :vartype notify_keyspace_events: str - :ivar preferred_data_archive_auth_method: Preferred auth method to communicate to storage - account used for data archive, specify SAS or ManagedIdentity, default value is SAS. - :vartype preferred_data_archive_auth_method: str - :ivar preferred_data_persistence_auth_method: Preferred auth method to communicate to storage - account used for data persistence, specify SAS or ManagedIdentity, default value is SAS. - :vartype preferred_data_persistence_auth_method: str - :ivar zonal_configuration: Zonal Configuration. - :vartype zonal_configuration: str - :ivar authnotrequired: Specifies whether the authentication is disabled. Setting this property - is highly discouraged from security point of view. - :vartype authnotrequired: str - :ivar storage_subscription_id: SubscriptionId of the storage account for persistence (aof/rdb) - using ManagedIdentity. - :vartype storage_subscription_id: str - :ivar aad_enabled: Specifies whether AAD based authentication has been enabled or disabled for - the cache. - :vartype aad_enabled: str - """ - - _validation = { - "maxclients": {"readonly": True}, - "preferred_data_archive_auth_method": {"readonly": True}, - "zonal_configuration": {"readonly": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "rdb_backup_enabled": {"key": "rdb-backup-enabled", "type": "str"}, - "rdb_backup_frequency": {"key": "rdb-backup-frequency", "type": "str"}, - "rdb_backup_max_snapshot_count": {"key": "rdb-backup-max-snapshot-count", "type": "str"}, - "rdb_storage_connection_string": {"key": "rdb-storage-connection-string", "type": "str"}, - "aof_backup_enabled": {"key": "aof-backup-enabled", "type": "str"}, - "aof_storage_connection_string0": {"key": "aof-storage-connection-string-0", "type": "str"}, - "aof_storage_connection_string1": {"key": "aof-storage-connection-string-1", "type": "str"}, - "maxfragmentationmemory_reserved": {"key": "maxfragmentationmemory-reserved", "type": "str"}, - "maxmemory_policy": {"key": "maxmemory-policy", "type": "str"}, - "maxmemory_reserved": {"key": "maxmemory-reserved", "type": "str"}, - "maxmemory_delta": {"key": "maxmemory-delta", "type": "str"}, - "maxclients": {"key": "maxclients", "type": "str"}, - "notify_keyspace_events": {"key": "notify-keyspace-events", "type": "str"}, - "preferred_data_archive_auth_method": {"key": "preferred-data-archive-auth-method", "type": "str"}, - "preferred_data_persistence_auth_method": {"key": "preferred-data-persistence-auth-method", "type": "str"}, - "zonal_configuration": {"key": "zonal-configuration", "type": "str"}, - "authnotrequired": {"key": "authnotrequired", "type": "str"}, - "storage_subscription_id": {"key": "storage-subscription-id", "type": "str"}, - "aad_enabled": {"key": "aad-enabled", "type": "str"}, - } - - def __init__( - self, - *, - additional_properties: Optional[Dict[str, Any]] = None, - rdb_backup_enabled: Optional[str] = None, - rdb_backup_frequency: Optional[str] = None, - rdb_backup_max_snapshot_count: Optional[str] = None, - rdb_storage_connection_string: Optional[str] = None, - aof_backup_enabled: Optional[str] = None, - aof_storage_connection_string0: Optional[str] = None, - aof_storage_connection_string1: Optional[str] = None, - maxfragmentationmemory_reserved: Optional[str] = None, - maxmemory_policy: Optional[str] = None, - maxmemory_reserved: Optional[str] = None, - maxmemory_delta: Optional[str] = None, - notify_keyspace_events: Optional[str] = None, - preferred_data_persistence_auth_method: Optional[str] = None, - authnotrequired: Optional[str] = None, - storage_subscription_id: Optional[str] = None, - aad_enabled: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword additional_properties: Unmatched properties from the message are deserialized to this - collection. - :paramtype additional_properties: dict[str, any] - :keyword rdb_backup_enabled: Specifies whether the rdb backup is enabled. - :paramtype rdb_backup_enabled: str - :keyword rdb_backup_frequency: Specifies the frequency for creating rdb backup in minutes. - Valid values: (15, 30, 60, 360, 720, 1440). - :paramtype rdb_backup_frequency: str - :keyword rdb_backup_max_snapshot_count: Specifies the maximum number of snapshots for rdb - backup. - :paramtype rdb_backup_max_snapshot_count: str - :keyword rdb_storage_connection_string: The storage account connection string for storing rdb - file. - :paramtype rdb_storage_connection_string: str - :keyword aof_backup_enabled: Specifies whether the aof backup is enabled. - :paramtype aof_backup_enabled: str - :keyword aof_storage_connection_string0: First storage account connection string. - :paramtype aof_storage_connection_string0: str - :keyword aof_storage_connection_string1: Second storage account connection string. - :paramtype aof_storage_connection_string1: str - :keyword maxfragmentationmemory_reserved: Value in megabytes reserved for fragmentation per - shard. - :paramtype maxfragmentationmemory_reserved: str - :keyword maxmemory_policy: The eviction strategy used when your data won't fit within its - memory limit. - :paramtype maxmemory_policy: str - :keyword maxmemory_reserved: Value in megabytes reserved for non-cache usage per shard e.g. - failover. - :paramtype maxmemory_reserved: str - :keyword maxmemory_delta: Value in megabytes reserved for non-cache usage per shard e.g. - failover. - :paramtype maxmemory_delta: str - :keyword notify_keyspace_events: The keyspace events which should be monitored. - :paramtype notify_keyspace_events: str - :keyword preferred_data_persistence_auth_method: Preferred auth method to communicate to - storage account used for data persistence, specify SAS or ManagedIdentity, default value is - SAS. - :paramtype preferred_data_persistence_auth_method: str - :keyword authnotrequired: Specifies whether the authentication is disabled. Setting this - property is highly discouraged from security point of view. - :paramtype authnotrequired: str - :keyword storage_subscription_id: SubscriptionId of the storage account for persistence - (aof/rdb) using ManagedIdentity. - :paramtype storage_subscription_id: str - :keyword aad_enabled: Specifies whether AAD based authentication has been enabled or disabled - for the cache. - :paramtype aad_enabled: str - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.rdb_backup_enabled = rdb_backup_enabled - self.rdb_backup_frequency = rdb_backup_frequency - self.rdb_backup_max_snapshot_count = rdb_backup_max_snapshot_count - self.rdb_storage_connection_string = rdb_storage_connection_string - self.aof_backup_enabled = aof_backup_enabled - self.aof_storage_connection_string0 = aof_storage_connection_string0 - self.aof_storage_connection_string1 = aof_storage_connection_string1 - self.maxfragmentationmemory_reserved = maxfragmentationmemory_reserved - self.maxmemory_policy = maxmemory_policy - self.maxmemory_reserved = maxmemory_reserved - self.maxmemory_delta = maxmemory_delta - self.maxclients = None - self.notify_keyspace_events = notify_keyspace_events - self.preferred_data_archive_auth_method = None - self.preferred_data_persistence_auth_method = preferred_data_persistence_auth_method - self.zonal_configuration = None - self.authnotrequired = authnotrequired - self.storage_subscription_id = storage_subscription_id - self.aad_enabled = aad_enabled - - -class RedisCreateParameters(_serialization.Model): - """Parameters supplied to the Create Redis operation. - - All required parameters must be populated in order to send to server. - - :ivar zones: A list of availability zones denoting where the resource needs to come from. - :vartype zones: list[str] - :ivar location: The geo-location where the resource lives. Required. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar identity: The identity of the resource. - :vartype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity - :ivar redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is - required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :vartype redis_version: str - :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. - :vartype enable_non_ssl_port: bool - :ivar replicas_per_master: The number of replicas to be created per primary. - :vartype replicas_per_master: int - :ivar replicas_per_primary: The number of replicas to be created per primary. - :vartype replicas_per_primary: int - :ivar tenant_settings: A dictionary of tenant settings. - :vartype tenant_settings: dict[str, str] - :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. - :vartype shard_count: int - :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. - Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private - endpoints are the exclusive access method. Default value is 'Enabled'. Known values are: - "Enabled" and "Disabled". - :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your - Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at - least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :ivar disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :vartype disable_access_key_authentication: bool - :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the - Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :ivar sku: The SKU of the Redis cache to deploy. Required. - :vartype sku: ~azure.mgmt.redis.models.Sku - :ivar subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :vartype subnet_id: str - :ivar static_ip: Static IP address. Optionally, may be specified when deploying a Redis cache - inside an existing Azure Virtual Network; auto assigned by default. - :vartype static_ip: str - """ - - _validation = { - "location": {"required": True}, - "sku": {"required": True}, - "subnet_id": { - "pattern": r"^/subscriptions/[^/]*/resourceGroups/[^/]*/providers/Microsoft.(ClassicNetwork|Network)/virtualNetworks/[^/]*/subnets/[^/]*$" - }, - "static_ip": {"pattern": r"^\d+\.\d+\.\d+\.\d+$"}, - } - - _attribute_map = { - "zones": {"key": "zones", "type": "[str]"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "redis_configuration": { - "key": "properties.redisConfiguration", - "type": "RedisCommonPropertiesRedisConfiguration", - }, - "redis_version": {"key": "properties.redisVersion", "type": "str"}, - "enable_non_ssl_port": {"key": "properties.enableNonSslPort", "type": "bool"}, - "replicas_per_master": {"key": "properties.replicasPerMaster", "type": "int"}, - "replicas_per_primary": {"key": "properties.replicasPerPrimary", "type": "int"}, - "tenant_settings": {"key": "properties.tenantSettings", "type": "{str}"}, - "shard_count": {"key": "properties.shardCount", "type": "int"}, - "minimum_tls_version": {"key": "properties.minimumTlsVersion", "type": "str"}, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, - "update_channel": {"key": "properties.updateChannel", "type": "str"}, - "disable_access_key_authentication": {"key": "properties.disableAccessKeyAuthentication", "type": "bool"}, - "zonal_allocation_policy": {"key": "properties.zonalAllocationPolicy", "type": "str"}, - "sku": {"key": "properties.sku", "type": "Sku"}, - "subnet_id": {"key": "properties.subnetId", "type": "str"}, - "static_ip": {"key": "properties.staticIP", "type": "str"}, - } - - def __init__( - self, - *, - location: str, - sku: "_models.Sku", - zones: Optional[List[str]] = None, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, - redis_version: Optional[str] = None, - enable_non_ssl_port: bool = False, - replicas_per_master: Optional[int] = None, - replicas_per_primary: Optional[int] = None, - tenant_settings: Optional[Dict[str, str]] = None, - shard_count: Optional[int] = None, - minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, - public_network_access: Union[str, "_models.PublicNetworkAccess"] = "Enabled", - update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, - disable_access_key_authentication: bool = False, - zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, - subnet_id: Optional[str] = None, - static_ip: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword zones: A list of availability zones denoting where the resource needs to come from. - :paramtype zones: list[str] - :keyword location: The geo-location where the resource lives. Required. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword identity: The identity of the resource. - :paramtype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity - :keyword redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :paramtype redis_configuration: - ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :keyword redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' - is required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :paramtype redis_version: str - :keyword enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is - enabled. - :paramtype enable_non_ssl_port: bool - :keyword replicas_per_master: The number of replicas to be created per primary. - :paramtype replicas_per_master: int - :keyword replicas_per_primary: The number of replicas to be created per primary. - :paramtype replicas_per_primary: int - :keyword tenant_settings: A dictionary of tenant settings. - :paramtype tenant_settings: dict[str, str] - :keyword shard_count: The number of shards to be created on a Premium Cluster Cache. - :paramtype shard_count: int - :keyword minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :paramtype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :keyword public_network_access: Whether or not public endpoint access is allowed for this - cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', - private endpoints are the exclusive access method. Default value is 'Enabled'. Known values - are: "Enabled" and "Disabled". - :paramtype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :keyword update_channel: Optional: Specifies the update channel for the monthly Redis updates - your Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates - at least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :paramtype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :keyword disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :paramtype disable_access_key_authentication: bool - :keyword zonal_allocation_policy: Optional: Specifies how availability zones are allocated to - the Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :paramtype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :keyword sku: The SKU of the Redis cache to deploy. Required. - :paramtype sku: ~azure.mgmt.redis.models.Sku - :keyword subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :paramtype subnet_id: str - :keyword static_ip: Static IP address. Optionally, may be specified when deploying a Redis - cache inside an existing Azure Virtual Network; auto assigned by default. - :paramtype static_ip: str - """ - super().__init__(**kwargs) - self.zones = zones - self.location = location - self.tags = tags - self.identity = identity - self.redis_configuration = redis_configuration - self.redis_version = redis_version - self.enable_non_ssl_port = enable_non_ssl_port - self.replicas_per_master = replicas_per_master - self.replicas_per_primary = replicas_per_primary - self.tenant_settings = tenant_settings - self.shard_count = shard_count - self.minimum_tls_version = minimum_tls_version - self.public_network_access = public_network_access - self.update_channel = update_channel - self.disable_access_key_authentication = disable_access_key_authentication - self.zonal_allocation_policy = zonal_allocation_policy - self.sku = sku - self.subnet_id = subnet_id - self.static_ip = static_ip - - -class RedisCreateProperties(RedisCommonProperties): - """Properties supplied to Create Redis operation. - - All required parameters must be populated in order to send to server. - - :ivar redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is - required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :vartype redis_version: str - :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. - :vartype enable_non_ssl_port: bool - :ivar replicas_per_master: The number of replicas to be created per primary. - :vartype replicas_per_master: int - :ivar replicas_per_primary: The number of replicas to be created per primary. - :vartype replicas_per_primary: int - :ivar tenant_settings: A dictionary of tenant settings. - :vartype tenant_settings: dict[str, str] - :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. - :vartype shard_count: int - :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. - Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private - endpoints are the exclusive access method. Default value is 'Enabled'. Known values are: - "Enabled" and "Disabled". - :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your - Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at - least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :ivar disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :vartype disable_access_key_authentication: bool - :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the - Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :ivar sku: The SKU of the Redis cache to deploy. Required. - :vartype sku: ~azure.mgmt.redis.models.Sku - :ivar subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :vartype subnet_id: str - :ivar static_ip: Static IP address. Optionally, may be specified when deploying a Redis cache - inside an existing Azure Virtual Network; auto assigned by default. - :vartype static_ip: str - """ - - _validation = { - "sku": {"required": True}, - "subnet_id": { - "pattern": r"^/subscriptions/[^/]*/resourceGroups/[^/]*/providers/Microsoft.(ClassicNetwork|Network)/virtualNetworks/[^/]*/subnets/[^/]*$" - }, - "static_ip": {"pattern": r"^\d+\.\d+\.\d+\.\d+$"}, - } - - _attribute_map = { - "redis_configuration": {"key": "redisConfiguration", "type": "RedisCommonPropertiesRedisConfiguration"}, - "redis_version": {"key": "redisVersion", "type": "str"}, - "enable_non_ssl_port": {"key": "enableNonSslPort", "type": "bool"}, - "replicas_per_master": {"key": "replicasPerMaster", "type": "int"}, - "replicas_per_primary": {"key": "replicasPerPrimary", "type": "int"}, - "tenant_settings": {"key": "tenantSettings", "type": "{str}"}, - "shard_count": {"key": "shardCount", "type": "int"}, - "minimum_tls_version": {"key": "minimumTlsVersion", "type": "str"}, - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - "update_channel": {"key": "updateChannel", "type": "str"}, - "disable_access_key_authentication": {"key": "disableAccessKeyAuthentication", "type": "bool"}, - "zonal_allocation_policy": {"key": "zonalAllocationPolicy", "type": "str"}, - "sku": {"key": "sku", "type": "Sku"}, - "subnet_id": {"key": "subnetId", "type": "str"}, - "static_ip": {"key": "staticIP", "type": "str"}, - } - - def __init__( - self, - *, - sku: "_models.Sku", - redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, - redis_version: Optional[str] = None, - enable_non_ssl_port: bool = False, - replicas_per_master: Optional[int] = None, - replicas_per_primary: Optional[int] = None, - tenant_settings: Optional[Dict[str, str]] = None, - shard_count: Optional[int] = None, - minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, - public_network_access: Union[str, "_models.PublicNetworkAccess"] = "Enabled", - update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, - disable_access_key_authentication: bool = False, - zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, - subnet_id: Optional[str] = None, - static_ip: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :paramtype redis_configuration: - ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :keyword redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' - is required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :paramtype redis_version: str - :keyword enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is - enabled. - :paramtype enable_non_ssl_port: bool - :keyword replicas_per_master: The number of replicas to be created per primary. - :paramtype replicas_per_master: int - :keyword replicas_per_primary: The number of replicas to be created per primary. - :paramtype replicas_per_primary: int - :keyword tenant_settings: A dictionary of tenant settings. - :paramtype tenant_settings: dict[str, str] - :keyword shard_count: The number of shards to be created on a Premium Cluster Cache. - :paramtype shard_count: int - :keyword minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :paramtype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :keyword public_network_access: Whether or not public endpoint access is allowed for this - cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', - private endpoints are the exclusive access method. Default value is 'Enabled'. Known values - are: "Enabled" and "Disabled". - :paramtype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :keyword update_channel: Optional: Specifies the update channel for the monthly Redis updates - your Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates - at least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :paramtype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :keyword disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :paramtype disable_access_key_authentication: bool - :keyword zonal_allocation_policy: Optional: Specifies how availability zones are allocated to - the Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :paramtype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :keyword sku: The SKU of the Redis cache to deploy. Required. - :paramtype sku: ~azure.mgmt.redis.models.Sku - :keyword subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :paramtype subnet_id: str - :keyword static_ip: Static IP address. Optionally, may be specified when deploying a Redis - cache inside an existing Azure Virtual Network; auto assigned by default. - :paramtype static_ip: str - """ - super().__init__( - redis_configuration=redis_configuration, - redis_version=redis_version, - enable_non_ssl_port=enable_non_ssl_port, - replicas_per_master=replicas_per_master, - replicas_per_primary=replicas_per_primary, - tenant_settings=tenant_settings, - shard_count=shard_count, - minimum_tls_version=minimum_tls_version, - public_network_access=public_network_access, - update_channel=update_channel, - disable_access_key_authentication=disable_access_key_authentication, - zonal_allocation_policy=zonal_allocation_policy, - **kwargs - ) - self.sku = sku - self.subnet_id = subnet_id - self.static_ip = static_ip - - -class RedisFirewallRule(ProxyResource): - """A firewall rule on a redis cache has a name, and describes a contiguous range of IP addresses - permitted to connect. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 start_ip: lowest IP address included in the range. Required. - :vartype start_ip: str - :ivar end_ip: highest IP address included in the range. Required. - :vartype end_ip: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "start_ip": {"required": True}, - "end_ip": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "start_ip": {"key": "properties.startIP", "type": "str"}, - "end_ip": {"key": "properties.endIP", "type": "str"}, - } - - def __init__(self, *, start_ip: str, end_ip: str, **kwargs: Any) -> None: - """ - :keyword start_ip: lowest IP address included in the range. Required. - :paramtype start_ip: str - :keyword end_ip: highest IP address included in the range. Required. - :paramtype end_ip: str - """ - super().__init__(**kwargs) - self.start_ip = start_ip - self.end_ip = end_ip - - -class RedisFirewallRuleCreateParameters(RedisFirewallRule): - """Parameters required for creating a firewall rule on redis cache. (Note, you can just use the - FirewallRule type instead now.). - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 start_ip: lowest IP address included in the range. Required. - :vartype start_ip: str - :ivar end_ip: highest IP address included in the range. Required. - :vartype end_ip: str - """ - - -class RedisFirewallRuleListResult(_serialization.Model): - """The response of list firewall rules Redis operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Results of the list firewall rules operation. - :vartype value: list[~azure.mgmt.redis.models.RedisFirewallRule] - :ivar next_link: Link for next page of results. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RedisFirewallRule]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[List["_models.RedisFirewallRule"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Results of the list firewall rules operation. - :paramtype value: list[~azure.mgmt.redis.models.RedisFirewallRule] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class RedisForceRebootResponse(_serialization.Model): - """Response to force reboot for Redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar message: Status message. - :vartype message: str - """ - - _validation = { - "message": {"readonly": True}, - } - - _attribute_map = { - "message": {"key": "message", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.message = None - - -class RedisInstanceDetails(_serialization.Model): - """Details of single instance of redis. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar ssl_port: Redis instance SSL port. - :vartype ssl_port: int - :ivar non_ssl_port: If enableNonSslPort is true, provides Redis instance Non-SSL port. - :vartype non_ssl_port: int - :ivar zone: If the Cache uses availability zones, specifies availability zone where this - instance is located. - :vartype zone: str - :ivar shard_id: If clustering is enabled, the Shard ID of Redis Instance. - :vartype shard_id: int - :ivar is_master: Specifies whether the instance is a primary node. - :vartype is_master: bool - :ivar is_primary: Specifies whether the instance is a primary node. - :vartype is_primary: bool - """ - - _validation = { - "ssl_port": {"readonly": True}, - "non_ssl_port": {"readonly": True}, - "zone": {"readonly": True}, - "shard_id": {"readonly": True}, - "is_master": {"readonly": True}, - "is_primary": {"readonly": True}, - } - - _attribute_map = { - "ssl_port": {"key": "sslPort", "type": "int"}, - "non_ssl_port": {"key": "nonSslPort", "type": "int"}, - "zone": {"key": "zone", "type": "str"}, - "shard_id": {"key": "shardId", "type": "int"}, - "is_master": {"key": "isMaster", "type": "bool"}, - "is_primary": {"key": "isPrimary", "type": "bool"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.ssl_port = None - self.non_ssl_port = None - self.zone = None - self.shard_id = None - self.is_master = None - self.is_primary = None - - -class RedisLinkedServer(_serialization.Model): - """Linked server Id. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Linked server Id. - :vartype id: str - """ - - _validation = { - "id": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.id = None - - -class RedisLinkedServerCreateParameters(_serialization.Model): - """Parameter required for creating a linked server to redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. - :vartype linked_redis_cache_id: str - :ivar linked_redis_cache_location: Location of the linked redis cache. Required. - :vartype linked_redis_cache_location: str - :ivar server_role: Role of the linked server. Required. Known values are: "Primary" and - "Secondary". - :vartype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - :ivar geo_replicated_primary_host_name: The unchanging DNS name which will always point to - current geo-primary cache among the linked redis caches for seamless Geo Failover experience. - :vartype geo_replicated_primary_host_name: str - :ivar primary_host_name: The changing DNS name that resolves to the current geo-primary cache - among the linked redis caches before or after the Geo Failover. - :vartype primary_host_name: str - """ - - _validation = { - "linked_redis_cache_id": {"required": True}, - "linked_redis_cache_location": {"required": True}, - "server_role": {"required": True}, - "geo_replicated_primary_host_name": {"readonly": True}, - "primary_host_name": {"readonly": True}, - } - - _attribute_map = { - "linked_redis_cache_id": {"key": "properties.linkedRedisCacheId", "type": "str"}, - "linked_redis_cache_location": {"key": "properties.linkedRedisCacheLocation", "type": "str"}, - "server_role": {"key": "properties.serverRole", "type": "str"}, - "geo_replicated_primary_host_name": {"key": "properties.geoReplicatedPrimaryHostName", "type": "str"}, - "primary_host_name": {"key": "properties.primaryHostName", "type": "str"}, - } - - def __init__( - self, - *, - linked_redis_cache_id: str, - linked_redis_cache_location: str, - server_role: Union[str, "_models.ReplicationRole"], - **kwargs: Any - ) -> None: - """ - :keyword linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. - :paramtype linked_redis_cache_id: str - :keyword linked_redis_cache_location: Location of the linked redis cache. Required. - :paramtype linked_redis_cache_location: str - :keyword server_role: Role of the linked server. Required. Known values are: "Primary" and - "Secondary". - :paramtype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - """ - super().__init__(**kwargs) - self.linked_redis_cache_id = linked_redis_cache_id - self.linked_redis_cache_location = linked_redis_cache_location - self.server_role = server_role - self.geo_replicated_primary_host_name = None - self.primary_host_name = None - - -class RedisLinkedServerCreateProperties(_serialization.Model): - """Create properties for a linked server. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. - :vartype linked_redis_cache_id: str - :ivar linked_redis_cache_location: Location of the linked redis cache. Required. - :vartype linked_redis_cache_location: str - :ivar server_role: Role of the linked server. Required. Known values are: "Primary" and - "Secondary". - :vartype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - :ivar geo_replicated_primary_host_name: The unchanging DNS name which will always point to - current geo-primary cache among the linked redis caches for seamless Geo Failover experience. - :vartype geo_replicated_primary_host_name: str - :ivar primary_host_name: The changing DNS name that resolves to the current geo-primary cache - among the linked redis caches before or after the Geo Failover. - :vartype primary_host_name: str - """ - - _validation = { - "linked_redis_cache_id": {"required": True}, - "linked_redis_cache_location": {"required": True}, - "server_role": {"required": True}, - "geo_replicated_primary_host_name": {"readonly": True}, - "primary_host_name": {"readonly": True}, - } - - _attribute_map = { - "linked_redis_cache_id": {"key": "linkedRedisCacheId", "type": "str"}, - "linked_redis_cache_location": {"key": "linkedRedisCacheLocation", "type": "str"}, - "server_role": {"key": "serverRole", "type": "str"}, - "geo_replicated_primary_host_name": {"key": "geoReplicatedPrimaryHostName", "type": "str"}, - "primary_host_name": {"key": "primaryHostName", "type": "str"}, - } - - def __init__( - self, - *, - linked_redis_cache_id: str, - linked_redis_cache_location: str, - server_role: Union[str, "_models.ReplicationRole"], - **kwargs: Any - ) -> None: - """ - :keyword linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. - :paramtype linked_redis_cache_id: str - :keyword linked_redis_cache_location: Location of the linked redis cache. Required. - :paramtype linked_redis_cache_location: str - :keyword server_role: Role of the linked server. Required. Known values are: "Primary" and - "Secondary". - :paramtype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - """ - super().__init__(**kwargs) - self.linked_redis_cache_id = linked_redis_cache_id - self.linked_redis_cache_location = linked_redis_cache_location - self.server_role = server_role - self.geo_replicated_primary_host_name = None - self.primary_host_name = None - - -class RedisLinkedServerProperties(RedisLinkedServerCreateProperties): - """Properties of a linked server to be returned in get/put response. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. - :vartype linked_redis_cache_id: str - :ivar linked_redis_cache_location: Location of the linked redis cache. Required. - :vartype linked_redis_cache_location: str - :ivar server_role: Role of the linked server. Required. Known values are: "Primary" and - "Secondary". - :vartype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - :ivar geo_replicated_primary_host_name: The unchanging DNS name which will always point to - current geo-primary cache among the linked redis caches for seamless Geo Failover experience. - :vartype geo_replicated_primary_host_name: str - :ivar primary_host_name: The changing DNS name that resolves to the current geo-primary cache - among the linked redis caches before or after the Geo Failover. - :vartype primary_host_name: str - :ivar provisioning_state: Terminal state of the link between primary and secondary redis cache. - :vartype provisioning_state: str - """ - - _validation = { - "linked_redis_cache_id": {"required": True}, - "linked_redis_cache_location": {"required": True}, - "server_role": {"required": True}, - "geo_replicated_primary_host_name": {"readonly": True}, - "primary_host_name": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "linked_redis_cache_id": {"key": "linkedRedisCacheId", "type": "str"}, - "linked_redis_cache_location": {"key": "linkedRedisCacheLocation", "type": "str"}, - "server_role": {"key": "serverRole", "type": "str"}, - "geo_replicated_primary_host_name": {"key": "geoReplicatedPrimaryHostName", "type": "str"}, - "primary_host_name": {"key": "primaryHostName", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - linked_redis_cache_id: str, - linked_redis_cache_location: str, - server_role: Union[str, "_models.ReplicationRole"], - **kwargs: Any - ) -> None: - """ - :keyword linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. Required. - :paramtype linked_redis_cache_id: str - :keyword linked_redis_cache_location: Location of the linked redis cache. Required. - :paramtype linked_redis_cache_location: str - :keyword server_role: Role of the linked server. Required. Known values are: "Primary" and - "Secondary". - :paramtype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - """ - super().__init__( - linked_redis_cache_id=linked_redis_cache_id, - linked_redis_cache_location=linked_redis_cache_location, - server_role=server_role, - **kwargs - ) - self.provisioning_state = None - - -class RedisLinkedServerWithProperties(ProxyResource): - """Response to put/get linked server (with properties) for Redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. - :vartype linked_redis_cache_id: str - :ivar linked_redis_cache_location: Location of the linked redis cache. - :vartype linked_redis_cache_location: str - :ivar server_role: Role of the linked server. Known values are: "Primary" and "Secondary". - :vartype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - :ivar geo_replicated_primary_host_name: The unchanging DNS name which will always point to - current geo-primary cache among the linked redis caches for seamless Geo Failover experience. - :vartype geo_replicated_primary_host_name: str - :ivar primary_host_name: The changing DNS name that resolves to the current geo-primary cache - among the linked redis caches before or after the Geo Failover. - :vartype primary_host_name: str - :ivar provisioning_state: Terminal state of the link between primary and secondary redis cache. - :vartype provisioning_state: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "geo_replicated_primary_host_name": {"readonly": True}, - "primary_host_name": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "linked_redis_cache_id": {"key": "properties.linkedRedisCacheId", "type": "str"}, - "linked_redis_cache_location": {"key": "properties.linkedRedisCacheLocation", "type": "str"}, - "server_role": {"key": "properties.serverRole", "type": "str"}, - "geo_replicated_primary_host_name": {"key": "properties.geoReplicatedPrimaryHostName", "type": "str"}, - "primary_host_name": {"key": "properties.primaryHostName", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - linked_redis_cache_id: Optional[str] = None, - linked_redis_cache_location: Optional[str] = None, - server_role: Optional[Union[str, "_models.ReplicationRole"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword linked_redis_cache_id: Fully qualified resourceId of the linked redis cache. - :paramtype linked_redis_cache_id: str - :keyword linked_redis_cache_location: Location of the linked redis cache. - :paramtype linked_redis_cache_location: str - :keyword server_role: Role of the linked server. Known values are: "Primary" and "Secondary". - :paramtype server_role: str or ~azure.mgmt.redis.models.ReplicationRole - """ - super().__init__(**kwargs) - self.linked_redis_cache_id = linked_redis_cache_id - self.linked_redis_cache_location = linked_redis_cache_location - self.server_role = server_role - self.geo_replicated_primary_host_name = None - self.primary_host_name = None - self.provisioning_state = None - - -class RedisLinkedServerWithPropertiesList(_serialization.Model): - """List of linked servers (with properties) of a Redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of linked servers (with properties) of a Redis cache. - :vartype value: list[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :ivar next_link: Link for next set. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RedisLinkedServerWithProperties]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[List["_models.RedisLinkedServerWithProperties"]] = None, **kwargs: Any - ) -> None: - """ - :keyword value: List of linked servers (with properties) of a Redis cache. - :paramtype value: list[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class RedisListResult(_serialization.Model): - """The response of list Redis operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of Redis cache instances. - :vartype value: list[~azure.mgmt.redis.models.RedisResource] - :ivar next_link: Link for next page of results. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RedisResource]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[List["_models.RedisResource"]] = None, **kwargs: Any) -> None: - """ - :keyword value: List of Redis cache instances. - :paramtype value: list[~azure.mgmt.redis.models.RedisResource] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class RedisPatchSchedule(ProxyResource): - """Response to put/get patch schedules for Redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 location: The geo-location where the resource lives. - :vartype location: str - :ivar schedule_entries: List of patch schedules for a Redis cache. Required. - :vartype schedule_entries: list[~azure.mgmt.redis.models.ScheduleEntry] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"readonly": True}, - "schedule_entries": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "schedule_entries": {"key": "properties.scheduleEntries", "type": "[ScheduleEntry]"}, - } - - def __init__(self, *, schedule_entries: List["_models.ScheduleEntry"], **kwargs: Any) -> None: - """ - :keyword schedule_entries: List of patch schedules for a Redis cache. Required. - :paramtype schedule_entries: list[~azure.mgmt.redis.models.ScheduleEntry] - """ - super().__init__(**kwargs) - self.location = None - self.schedule_entries = schedule_entries - - -class RedisPatchScheduleListResult(_serialization.Model): - """The response of list patch schedules Redis operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Results of the list patch schedules operation. - :vartype value: list[~azure.mgmt.redis.models.RedisPatchSchedule] - :ivar next_link: Link for next page of results. - :vartype next_link: str - """ - - _validation = { - "next_link": {"readonly": True}, - } - - _attribute_map = { - "value": {"key": "value", "type": "[RedisPatchSchedule]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__(self, *, value: Optional[List["_models.RedisPatchSchedule"]] = None, **kwargs: Any) -> None: - """ - :keyword value: Results of the list patch schedules operation. - :paramtype value: list[~azure.mgmt.redis.models.RedisPatchSchedule] - """ - super().__init__(**kwargs) - self.value = value - self.next_link = None - - -class RedisProperties(RedisCreateProperties): - """Properties of the redis cache. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is - required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :vartype redis_version: str - :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. - :vartype enable_non_ssl_port: bool - :ivar replicas_per_master: The number of replicas to be created per primary. - :vartype replicas_per_master: int - :ivar replicas_per_primary: The number of replicas to be created per primary. - :vartype replicas_per_primary: int - :ivar tenant_settings: A dictionary of tenant settings. - :vartype tenant_settings: dict[str, str] - :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. - :vartype shard_count: int - :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. - Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private - endpoints are the exclusive access method. Default value is 'Enabled'. Known values are: - "Enabled" and "Disabled". - :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your - Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at - least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :ivar disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :vartype disable_access_key_authentication: bool - :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the - Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :ivar sku: The SKU of the Redis cache to deploy. Required. - :vartype sku: ~azure.mgmt.redis.models.Sku - :ivar subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :vartype subnet_id: str - :ivar static_ip: Static IP address. Optionally, may be specified when deploying a Redis cache - inside an existing Azure Virtual Network; auto assigned by default. - :vartype static_ip: str - :ivar provisioning_state: Redis instance provisioning status. Known values are: "Creating", - "Deleting", "Disabled", "Failed", "Linking", "Provisioning", "RecoveringScaleFailure", - "Scaling", "Succeeded", "Unlinking", "Unprovisioning", "Updating", and "ConfiguringAAD". - :vartype provisioning_state: str or ~azure.mgmt.redis.models.ProvisioningState - :ivar host_name: Redis host name. - :vartype host_name: str - :ivar port: Redis non-SSL port. - :vartype port: int - :ivar ssl_port: Redis SSL port. - :vartype ssl_port: int - :ivar access_keys: The keys of the Redis cache - not set if this object is not the response to - Create or Update redis cache. - :vartype access_keys: ~azure.mgmt.redis.models.RedisAccessKeys - :ivar linked_servers: List of the linked servers associated with the cache. - :vartype linked_servers: list[~azure.mgmt.redis.models.RedisLinkedServer] - :ivar instances: List of the Redis instances associated with the cache. - :vartype instances: list[~azure.mgmt.redis.models.RedisInstanceDetails] - :ivar private_endpoint_connections: List of private endpoint connection associated with the - specified redis cache. - :vartype private_endpoint_connections: list[~azure.mgmt.redis.models.PrivateEndpointConnection] - """ - - _validation = { - "sku": {"required": True}, - "subnet_id": { - "pattern": r"^/subscriptions/[^/]*/resourceGroups/[^/]*/providers/Microsoft.(ClassicNetwork|Network)/virtualNetworks/[^/]*/subnets/[^/]*$" - }, - "static_ip": {"pattern": r"^\d+\.\d+\.\d+\.\d+$"}, - "provisioning_state": {"readonly": True}, - "host_name": {"readonly": True}, - "port": {"readonly": True}, - "ssl_port": {"readonly": True}, - "access_keys": {"readonly": True}, - "linked_servers": {"readonly": True}, - "instances": {"readonly": True}, - "private_endpoint_connections": {"readonly": True}, - } - - _attribute_map = { - "redis_configuration": {"key": "redisConfiguration", "type": "RedisCommonPropertiesRedisConfiguration"}, - "redis_version": {"key": "redisVersion", "type": "str"}, - "enable_non_ssl_port": {"key": "enableNonSslPort", "type": "bool"}, - "replicas_per_master": {"key": "replicasPerMaster", "type": "int"}, - "replicas_per_primary": {"key": "replicasPerPrimary", "type": "int"}, - "tenant_settings": {"key": "tenantSettings", "type": "{str}"}, - "shard_count": {"key": "shardCount", "type": "int"}, - "minimum_tls_version": {"key": "minimumTlsVersion", "type": "str"}, - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - "update_channel": {"key": "updateChannel", "type": "str"}, - "disable_access_key_authentication": {"key": "disableAccessKeyAuthentication", "type": "bool"}, - "zonal_allocation_policy": {"key": "zonalAllocationPolicy", "type": "str"}, - "sku": {"key": "sku", "type": "Sku"}, - "subnet_id": {"key": "subnetId", "type": "str"}, - "static_ip": {"key": "staticIP", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "host_name": {"key": "hostName", "type": "str"}, - "port": {"key": "port", "type": "int"}, - "ssl_port": {"key": "sslPort", "type": "int"}, - "access_keys": {"key": "accessKeys", "type": "RedisAccessKeys"}, - "linked_servers": {"key": "linkedServers", "type": "[RedisLinkedServer]"}, - "instances": {"key": "instances", "type": "[RedisInstanceDetails]"}, - "private_endpoint_connections": {"key": "privateEndpointConnections", "type": "[PrivateEndpointConnection]"}, - } - - def __init__( - self, - *, - sku: "_models.Sku", - redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, - redis_version: Optional[str] = None, - enable_non_ssl_port: bool = False, - replicas_per_master: Optional[int] = None, - replicas_per_primary: Optional[int] = None, - tenant_settings: Optional[Dict[str, str]] = None, - shard_count: Optional[int] = None, - minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, - public_network_access: Union[str, "_models.PublicNetworkAccess"] = "Enabled", - update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, - disable_access_key_authentication: bool = False, - zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, - subnet_id: Optional[str] = None, - static_ip: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :paramtype redis_configuration: - ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :keyword redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' - is required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :paramtype redis_version: str - :keyword enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is - enabled. - :paramtype enable_non_ssl_port: bool - :keyword replicas_per_master: The number of replicas to be created per primary. - :paramtype replicas_per_master: int - :keyword replicas_per_primary: The number of replicas to be created per primary. - :paramtype replicas_per_primary: int - :keyword tenant_settings: A dictionary of tenant settings. - :paramtype tenant_settings: dict[str, str] - :keyword shard_count: The number of shards to be created on a Premium Cluster Cache. - :paramtype shard_count: int - :keyword minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :paramtype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :keyword public_network_access: Whether or not public endpoint access is allowed for this - cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', - private endpoints are the exclusive access method. Default value is 'Enabled'. Known values - are: "Enabled" and "Disabled". - :paramtype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :keyword update_channel: Optional: Specifies the update channel for the monthly Redis updates - your Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates - at least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :paramtype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :keyword disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :paramtype disable_access_key_authentication: bool - :keyword zonal_allocation_policy: Optional: Specifies how availability zones are allocated to - the Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :paramtype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :keyword sku: The SKU of the Redis cache to deploy. Required. - :paramtype sku: ~azure.mgmt.redis.models.Sku - :keyword subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :paramtype subnet_id: str - :keyword static_ip: Static IP address. Optionally, may be specified when deploying a Redis - cache inside an existing Azure Virtual Network; auto assigned by default. - :paramtype static_ip: str - """ - super().__init__( - redis_configuration=redis_configuration, - redis_version=redis_version, - enable_non_ssl_port=enable_non_ssl_port, - replicas_per_master=replicas_per_master, - replicas_per_primary=replicas_per_primary, - tenant_settings=tenant_settings, - shard_count=shard_count, - minimum_tls_version=minimum_tls_version, - public_network_access=public_network_access, - update_channel=update_channel, - disable_access_key_authentication=disable_access_key_authentication, - zonal_allocation_policy=zonal_allocation_policy, - sku=sku, - subnet_id=subnet_id, - static_ip=static_ip, - **kwargs - ) - self.provisioning_state = None - self.host_name = None - self.port = None - self.ssl_port = None - self.access_keys = None - self.linked_servers = None - self.instances = None - self.private_endpoint_connections = None - - -class RedisRebootParameters(_serialization.Model): - """Specifies which Redis node(s) to reboot. - - :ivar reboot_type: Which Redis node(s) to reboot. Depending on this value data loss is - possible. Known values are: "PrimaryNode", "SecondaryNode", and "AllNodes". - :vartype reboot_type: str or ~azure.mgmt.redis.models.RebootType - :ivar shard_id: If clustering is enabled, the ID of the shard to be rebooted. - :vartype shard_id: int - :ivar ports: A list of redis instances to reboot, specified by per-instance SSL ports or - non-SSL ports. - :vartype ports: list[int] - """ - - _attribute_map = { - "reboot_type": {"key": "rebootType", "type": "str"}, - "shard_id": {"key": "shardId", "type": "int"}, - "ports": {"key": "ports", "type": "[int]"}, - } - - def __init__( - self, - *, - reboot_type: Optional[Union[str, "_models.RebootType"]] = None, - shard_id: Optional[int] = None, - ports: Optional[List[int]] = None, - **kwargs: Any - ) -> None: - """ - :keyword reboot_type: Which Redis node(s) to reboot. Depending on this value data loss is - possible. Known values are: "PrimaryNode", "SecondaryNode", and "AllNodes". - :paramtype reboot_type: str or ~azure.mgmt.redis.models.RebootType - :keyword shard_id: If clustering is enabled, the ID of the shard to be rebooted. - :paramtype shard_id: int - :keyword ports: A list of redis instances to reboot, specified by per-instance SSL ports or - non-SSL ports. - :paramtype ports: list[int] - """ - super().__init__(**kwargs) - self.reboot_type = reboot_type - self.shard_id = shard_id - self.ports = ports - - -class RedisRegenerateKeyParameters(_serialization.Model): - """Specifies which Redis access keys to reset. - - All required parameters must be populated in order to send to server. - - :ivar key_type: The Redis access key to regenerate. Required. Known values are: "Primary" and - "Secondary". - :vartype key_type: str or ~azure.mgmt.redis.models.RedisKeyType - """ - - _validation = { - "key_type": {"required": True}, - } - - _attribute_map = { - "key_type": {"key": "keyType", "type": "str"}, - } - - def __init__(self, *, key_type: Union[str, "_models.RedisKeyType"], **kwargs: Any) -> None: - """ - :keyword key_type: The Redis access key to regenerate. Required. Known values are: "Primary" - and "Secondary". - :paramtype key_type: str or ~azure.mgmt.redis.models.RedisKeyType - """ - super().__init__(**kwargs) - self.key_type = key_type - - -class TrackedResource(Resource): - """The resource model definition for an Azure Resource Manager tracked top level resource which - has 'tags' and a 'location'. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 tags: Resource tags. - :vartype tags: dict[str, str] - :ivar location: The geo-location where the resource lives. Required. - :vartype location: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "location": {"key": "location", "type": "str"}, - } - - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword location: The geo-location where the resource lives. Required. - :paramtype location: str - """ - super().__init__(**kwargs) - self.tags = tags - self.location = location - - -class RedisResource(TrackedResource): - """A single Redis item in List or Get Operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long - :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 tags: Resource tags. - :vartype tags: dict[str, str] - :ivar location: The geo-location where the resource lives. Required. - :vartype location: str - :ivar zones: A list of availability zones denoting where the resource needs to come from. - :vartype zones: list[str] - :ivar identity: The identity of the resource. - :vartype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity - :ivar redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is - required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :vartype redis_version: str - :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. - :vartype enable_non_ssl_port: bool - :ivar replicas_per_master: The number of replicas to be created per primary. - :vartype replicas_per_master: int - :ivar replicas_per_primary: The number of replicas to be created per primary. - :vartype replicas_per_primary: int - :ivar tenant_settings: A dictionary of tenant settings. - :vartype tenant_settings: dict[str, str] - :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. - :vartype shard_count: int - :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. - Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private - endpoints are the exclusive access method. Default value is 'Enabled'. Known values are: - "Enabled" and "Disabled". - :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your - Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at - least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :ivar disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :vartype disable_access_key_authentication: bool - :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the - Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :ivar sku: The SKU of the Redis cache to deploy. Required. - :vartype sku: ~azure.mgmt.redis.models.Sku - :ivar subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :vartype subnet_id: str - :ivar static_ip: Static IP address. Optionally, may be specified when deploying a Redis cache - inside an existing Azure Virtual Network; auto assigned by default. - :vartype static_ip: str - :ivar provisioning_state: Redis instance provisioning status. Known values are: "Creating", - "Deleting", "Disabled", "Failed", "Linking", "Provisioning", "RecoveringScaleFailure", - "Scaling", "Succeeded", "Unlinking", "Unprovisioning", "Updating", and "ConfiguringAAD". - :vartype provisioning_state: str or ~azure.mgmt.redis.models.ProvisioningState - :ivar host_name: Redis host name. - :vartype host_name: str - :ivar port: Redis non-SSL port. - :vartype port: int - :ivar ssl_port: Redis SSL port. - :vartype ssl_port: int - :ivar access_keys: The keys of the Redis cache - not set if this object is not the response to - Create or Update redis cache. - :vartype access_keys: ~azure.mgmt.redis.models.RedisAccessKeys - :ivar linked_servers: List of the linked servers associated with the cache. - :vartype linked_servers: list[~azure.mgmt.redis.models.RedisLinkedServer] - :ivar instances: List of the Redis instances associated with the cache. - :vartype instances: list[~azure.mgmt.redis.models.RedisInstanceDetails] - :ivar private_endpoint_connections: List of private endpoint connection associated with the - specified redis cache. - :vartype private_endpoint_connections: list[~azure.mgmt.redis.models.PrivateEndpointConnection] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"required": True}, - "sku": {"required": True}, - "subnet_id": { - "pattern": r"^/subscriptions/[^/]*/resourceGroups/[^/]*/providers/Microsoft.(ClassicNetwork|Network)/virtualNetworks/[^/]*/subnets/[^/]*$" - }, - "static_ip": {"pattern": r"^\d+\.\d+\.\d+\.\d+$"}, - "provisioning_state": {"readonly": True}, - "host_name": {"readonly": True}, - "port": {"readonly": True}, - "ssl_port": {"readonly": True}, - "access_keys": {"readonly": True}, - "linked_servers": {"readonly": True}, - "instances": {"readonly": True}, - "private_endpoint_connections": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "location": {"key": "location", "type": "str"}, - "zones": {"key": "zones", "type": "[str]"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "redis_configuration": { - "key": "properties.redisConfiguration", - "type": "RedisCommonPropertiesRedisConfiguration", - }, - "redis_version": {"key": "properties.redisVersion", "type": "str"}, - "enable_non_ssl_port": {"key": "properties.enableNonSslPort", "type": "bool"}, - "replicas_per_master": {"key": "properties.replicasPerMaster", "type": "int"}, - "replicas_per_primary": {"key": "properties.replicasPerPrimary", "type": "int"}, - "tenant_settings": {"key": "properties.tenantSettings", "type": "{str}"}, - "shard_count": {"key": "properties.shardCount", "type": "int"}, - "minimum_tls_version": {"key": "properties.minimumTlsVersion", "type": "str"}, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, - "update_channel": {"key": "properties.updateChannel", "type": "str"}, - "disable_access_key_authentication": {"key": "properties.disableAccessKeyAuthentication", "type": "bool"}, - "zonal_allocation_policy": {"key": "properties.zonalAllocationPolicy", "type": "str"}, - "sku": {"key": "properties.sku", "type": "Sku"}, - "subnet_id": {"key": "properties.subnetId", "type": "str"}, - "static_ip": {"key": "properties.staticIP", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "host_name": {"key": "properties.hostName", "type": "str"}, - "port": {"key": "properties.port", "type": "int"}, - "ssl_port": {"key": "properties.sslPort", "type": "int"}, - "access_keys": {"key": "properties.accessKeys", "type": "RedisAccessKeys"}, - "linked_servers": {"key": "properties.linkedServers", "type": "[RedisLinkedServer]"}, - "instances": {"key": "properties.instances", "type": "[RedisInstanceDetails]"}, - "private_endpoint_connections": { - "key": "properties.privateEndpointConnections", - "type": "[PrivateEndpointConnection]", - }, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - location: str, - sku: "_models.Sku", - tags: Optional[Dict[str, str]] = None, - zones: Optional[List[str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, - redis_version: Optional[str] = None, - enable_non_ssl_port: bool = False, - replicas_per_master: Optional[int] = None, - replicas_per_primary: Optional[int] = None, - tenant_settings: Optional[Dict[str, str]] = None, - shard_count: Optional[int] = None, - minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, - public_network_access: Union[str, "_models.PublicNetworkAccess"] = "Enabled", - update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, - disable_access_key_authentication: bool = False, - zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, - subnet_id: Optional[str] = None, - static_ip: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword location: The geo-location where the resource lives. Required. - :paramtype location: str - :keyword zones: A list of availability zones denoting where the resource needs to come from. - :paramtype zones: list[str] - :keyword identity: The identity of the resource. - :paramtype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity - :keyword redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :paramtype redis_configuration: - ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :keyword redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' - is required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :paramtype redis_version: str - :keyword enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is - enabled. - :paramtype enable_non_ssl_port: bool - :keyword replicas_per_master: The number of replicas to be created per primary. - :paramtype replicas_per_master: int - :keyword replicas_per_primary: The number of replicas to be created per primary. - :paramtype replicas_per_primary: int - :keyword tenant_settings: A dictionary of tenant settings. - :paramtype tenant_settings: dict[str, str] - :keyword shard_count: The number of shards to be created on a Premium Cluster Cache. - :paramtype shard_count: int - :keyword minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :paramtype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :keyword public_network_access: Whether or not public endpoint access is allowed for this - cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', - private endpoints are the exclusive access method. Default value is 'Enabled'. Known values - are: "Enabled" and "Disabled". - :paramtype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :keyword update_channel: Optional: Specifies the update channel for the monthly Redis updates - your Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates - at least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :paramtype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :keyword disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :paramtype disable_access_key_authentication: bool - :keyword zonal_allocation_policy: Optional: Specifies how availability zones are allocated to - the Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :paramtype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :keyword sku: The SKU of the Redis cache to deploy. Required. - :paramtype sku: ~azure.mgmt.redis.models.Sku - :keyword subnet_id: The full resource ID of a subnet in a virtual network to deploy the Redis - cache in. Example format: - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1. # pylint: disable=line-too-long - :paramtype subnet_id: str - :keyword static_ip: Static IP address. Optionally, may be specified when deploying a Redis - cache inside an existing Azure Virtual Network; auto assigned by default. - :paramtype static_ip: str - """ - super().__init__(tags=tags, location=location, **kwargs) - self.zones = zones - self.identity = identity - self.redis_configuration = redis_configuration - self.redis_version = redis_version - self.enable_non_ssl_port = enable_non_ssl_port - self.replicas_per_master = replicas_per_master - self.replicas_per_primary = replicas_per_primary - self.tenant_settings = tenant_settings - self.shard_count = shard_count - self.minimum_tls_version = minimum_tls_version - self.public_network_access = public_network_access - self.update_channel = update_channel - self.disable_access_key_authentication = disable_access_key_authentication - self.zonal_allocation_policy = zonal_allocation_policy - self.sku = sku - self.subnet_id = subnet_id - self.static_ip = static_ip - self.provisioning_state = None - self.host_name = None - self.port = None - self.ssl_port = None - self.access_keys = None - self.linked_servers = None - self.instances = None - self.private_endpoint_connections = None - - -class RedisUpdateParameters(_serialization.Model): - """Parameters supplied to the Update Redis operation. - - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar identity: The identity of the resource. - :vartype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity - :ivar redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is - required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :vartype redis_version: str - :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. - :vartype enable_non_ssl_port: bool - :ivar replicas_per_master: The number of replicas to be created per primary. - :vartype replicas_per_master: int - :ivar replicas_per_primary: The number of replicas to be created per primary. - :vartype replicas_per_primary: int - :ivar tenant_settings: A dictionary of tenant settings. - :vartype tenant_settings: dict[str, str] - :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. - :vartype shard_count: int - :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. - Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private - endpoints are the exclusive access method. Default value is 'Enabled'. Known values are: - "Enabled" and "Disabled". - :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your - Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at - least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :ivar disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :vartype disable_access_key_authentication: bool - :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the - Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :ivar sku: The SKU of the Redis cache to deploy. - :vartype sku: ~azure.mgmt.redis.models.Sku - """ - - _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - "identity": {"key": "identity", "type": "ManagedServiceIdentity"}, - "redis_configuration": { - "key": "properties.redisConfiguration", - "type": "RedisCommonPropertiesRedisConfiguration", - }, - "redis_version": {"key": "properties.redisVersion", "type": "str"}, - "enable_non_ssl_port": {"key": "properties.enableNonSslPort", "type": "bool"}, - "replicas_per_master": {"key": "properties.replicasPerMaster", "type": "int"}, - "replicas_per_primary": {"key": "properties.replicasPerPrimary", "type": "int"}, - "tenant_settings": {"key": "properties.tenantSettings", "type": "{str}"}, - "shard_count": {"key": "properties.shardCount", "type": "int"}, - "minimum_tls_version": {"key": "properties.minimumTlsVersion", "type": "str"}, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, - "update_channel": {"key": "properties.updateChannel", "type": "str"}, - "disable_access_key_authentication": {"key": "properties.disableAccessKeyAuthentication", "type": "bool"}, - "zonal_allocation_policy": {"key": "properties.zonalAllocationPolicy", "type": "str"}, - "sku": {"key": "properties.sku", "type": "Sku"}, - } - - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - identity: Optional["_models.ManagedServiceIdentity"] = None, - redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, - redis_version: Optional[str] = None, - enable_non_ssl_port: bool = False, - replicas_per_master: Optional[int] = None, - replicas_per_primary: Optional[int] = None, - tenant_settings: Optional[Dict[str, str]] = None, - shard_count: Optional[int] = None, - minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, - public_network_access: Union[str, "_models.PublicNetworkAccess"] = "Enabled", - update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, - disable_access_key_authentication: bool = False, - zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, - sku: Optional["_models.Sku"] = None, - **kwargs: Any - ) -> None: - """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword identity: The identity of the resource. - :paramtype identity: ~azure.mgmt.redis.models.ManagedServiceIdentity - :keyword redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :paramtype redis_configuration: - ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :keyword redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' - is required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :paramtype redis_version: str - :keyword enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is - enabled. - :paramtype enable_non_ssl_port: bool - :keyword replicas_per_master: The number of replicas to be created per primary. - :paramtype replicas_per_master: int - :keyword replicas_per_primary: The number of replicas to be created per primary. - :paramtype replicas_per_primary: int - :keyword tenant_settings: A dictionary of tenant settings. - :paramtype tenant_settings: dict[str, str] - :keyword shard_count: The number of shards to be created on a Premium Cluster Cache. - :paramtype shard_count: int - :keyword minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :paramtype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :keyword public_network_access: Whether or not public endpoint access is allowed for this - cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', - private endpoints are the exclusive access method. Default value is 'Enabled'. Known values - are: "Enabled" and "Disabled". - :paramtype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :keyword update_channel: Optional: Specifies the update channel for the monthly Redis updates - your Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates - at least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :paramtype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :keyword disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :paramtype disable_access_key_authentication: bool - :keyword zonal_allocation_policy: Optional: Specifies how availability zones are allocated to - the Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :paramtype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :keyword sku: The SKU of the Redis cache to deploy. - :paramtype sku: ~azure.mgmt.redis.models.Sku - """ - super().__init__(**kwargs) - self.tags = tags - self.identity = identity - self.redis_configuration = redis_configuration - self.redis_version = redis_version - self.enable_non_ssl_port = enable_non_ssl_port - self.replicas_per_master = replicas_per_master - self.replicas_per_primary = replicas_per_primary - self.tenant_settings = tenant_settings - self.shard_count = shard_count - self.minimum_tls_version = minimum_tls_version - self.public_network_access = public_network_access - self.update_channel = update_channel - self.disable_access_key_authentication = disable_access_key_authentication - self.zonal_allocation_policy = zonal_allocation_policy - self.sku = sku - - -class RedisUpdateProperties(RedisCommonProperties): - """Patchable properties of the redis cache. - - :ivar redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :vartype redis_configuration: ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :ivar redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' is - required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :vartype redis_version: str - :ivar enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is enabled. - :vartype enable_non_ssl_port: bool - :ivar replicas_per_master: The number of replicas to be created per primary. - :vartype replicas_per_master: int - :ivar replicas_per_primary: The number of replicas to be created per primary. - :vartype replicas_per_primary: int - :ivar tenant_settings: A dictionary of tenant settings. - :vartype tenant_settings: dict[str, str] - :ivar shard_count: The number of shards to be created on a Premium Cluster Cache. - :vartype shard_count: int - :ivar minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :vartype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :ivar public_network_access: Whether or not public endpoint access is allowed for this cache. - Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private - endpoints are the exclusive access method. Default value is 'Enabled'. Known values are: - "Enabled" and "Disabled". - :vartype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :ivar update_channel: Optional: Specifies the update channel for the monthly Redis updates your - Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates at - least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :vartype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :ivar disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :vartype disable_access_key_authentication: bool - :ivar zonal_allocation_policy: Optional: Specifies how availability zones are allocated to the - Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :vartype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :ivar sku: The SKU of the Redis cache to deploy. - :vartype sku: ~azure.mgmt.redis.models.Sku - """ - - _attribute_map = { - "redis_configuration": {"key": "redisConfiguration", "type": "RedisCommonPropertiesRedisConfiguration"}, - "redis_version": {"key": "redisVersion", "type": "str"}, - "enable_non_ssl_port": {"key": "enableNonSslPort", "type": "bool"}, - "replicas_per_master": {"key": "replicasPerMaster", "type": "int"}, - "replicas_per_primary": {"key": "replicasPerPrimary", "type": "int"}, - "tenant_settings": {"key": "tenantSettings", "type": "{str}"}, - "shard_count": {"key": "shardCount", "type": "int"}, - "minimum_tls_version": {"key": "minimumTlsVersion", "type": "str"}, - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - "update_channel": {"key": "updateChannel", "type": "str"}, - "disable_access_key_authentication": {"key": "disableAccessKeyAuthentication", "type": "bool"}, - "zonal_allocation_policy": {"key": "zonalAllocationPolicy", "type": "str"}, - "sku": {"key": "sku", "type": "Sku"}, - } - - def __init__( - self, - *, - redis_configuration: Optional["_models.RedisCommonPropertiesRedisConfiguration"] = None, - redis_version: Optional[str] = None, - enable_non_ssl_port: bool = False, - replicas_per_master: Optional[int] = None, - replicas_per_primary: Optional[int] = None, - tenant_settings: Optional[Dict[str, str]] = None, - shard_count: Optional[int] = None, - minimum_tls_version: Optional[Union[str, "_models.TlsVersion"]] = None, - public_network_access: Union[str, "_models.PublicNetworkAccess"] = "Enabled", - update_channel: Optional[Union[str, "_models.UpdateChannel"]] = None, - disable_access_key_authentication: bool = False, - zonal_allocation_policy: Optional[Union[str, "_models.ZonalAllocationPolicy"]] = None, - sku: Optional["_models.Sku"] = None, - **kwargs: Any - ) -> None: - """ - :keyword redis_configuration: All Redis Settings. Few possible keys: - rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta, - maxmemory-policy,notify-keyspace-events, aof-backup-enabled, aof-storage-connection-string-0, - aof-storage-connection-string-1 etc. - :paramtype redis_configuration: - ~azure.mgmt.redis.models.RedisCommonPropertiesRedisConfiguration - :keyword redis_version: Redis version. This should be in the form 'major[.minor]' (only 'major' - is required) or the value 'latest' which refers to the latest stable Redis version that is - available. Supported versions: 4.0, 6.0 (latest). Default value is 'latest'. - :paramtype redis_version: str - :keyword enable_non_ssl_port: Specifies whether the non-ssl Redis server port (6379) is - enabled. - :paramtype enable_non_ssl_port: bool - :keyword replicas_per_master: The number of replicas to be created per primary. - :paramtype replicas_per_master: int - :keyword replicas_per_primary: The number of replicas to be created per primary. - :paramtype replicas_per_primary: int - :keyword tenant_settings: A dictionary of tenant settings. - :paramtype tenant_settings: dict[str, str] - :keyword shard_count: The number of shards to be created on a Premium Cluster Cache. - :paramtype shard_count: int - :keyword minimum_tls_version: Optional: requires clients to use a specified TLS version (or - higher) to connect (e,g, '1.0', '1.1', '1.2'). Known values are: "1.0", "1.1", and "1.2". - :paramtype minimum_tls_version: str or ~azure.mgmt.redis.models.TlsVersion - :keyword public_network_access: Whether or not public endpoint access is allowed for this - cache. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', - private endpoints are the exclusive access method. Default value is 'Enabled'. Known values - are: "Enabled" and "Disabled". - :paramtype public_network_access: str or ~azure.mgmt.redis.models.PublicNetworkAccess - :keyword update_channel: Optional: Specifies the update channel for the monthly Redis updates - your Redis Cache will receive. Caches using 'Preview' update channel get latest Redis updates - at least 4 weeks ahead of 'Stable' channel caches. Default value is 'Stable'. Known values are: - "Stable" and "Preview". - :paramtype update_channel: str or ~azure.mgmt.redis.models.UpdateChannel - :keyword disable_access_key_authentication: Authentication to Redis through access keys is - disabled when set as true. Default value is false. - :paramtype disable_access_key_authentication: bool - :keyword zonal_allocation_policy: Optional: Specifies how availability zones are allocated to - the Redis cache. 'Automatic' enables zone redundancy and Azure will automatically select zones - based on regional availability and capacity. 'UserDefined' will select availability zones - passed in by you using the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If - 'zonalAllocationPolicy' is not passed, it will be set to 'UserDefined' when zones are passed - in, otherwise, it will be set to 'Automatic' in regions where zones are supported and 'NoZones' - in regions where zones are not supported. Known values are: "Automatic", "UserDefined", and - "NoZones". - :paramtype zonal_allocation_policy: str or ~azure.mgmt.redis.models.ZonalAllocationPolicy - :keyword sku: The SKU of the Redis cache to deploy. - :paramtype sku: ~azure.mgmt.redis.models.Sku - """ - super().__init__( - redis_configuration=redis_configuration, - redis_version=redis_version, - enable_non_ssl_port=enable_non_ssl_port, - replicas_per_master=replicas_per_master, - replicas_per_primary=replicas_per_primary, - tenant_settings=tenant_settings, - shard_count=shard_count, - minimum_tls_version=minimum_tls_version, - public_network_access=public_network_access, - update_channel=update_channel, - disable_access_key_authentication=disable_access_key_authentication, - zonal_allocation_policy=zonal_allocation_policy, - **kwargs - ) - self.sku = sku - - -class ScheduleEntry(_serialization.Model): - """Patch schedule entry for a Premium Redis Cache. - - All required parameters must be populated in order to send to server. - - :ivar day_of_week: Day of the week when a cache can be patched. Required. Known values are: - "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Everyday", and - "Weekend". - :vartype day_of_week: str or ~azure.mgmt.redis.models.DayOfWeek - :ivar start_hour_utc: Start hour after which cache patching can start. Required. - :vartype start_hour_utc: int - :ivar maintenance_window: ISO8601 timespan specifying how much time cache patching can take. - :vartype maintenance_window: ~datetime.timedelta - """ - - _validation = { - "day_of_week": {"required": True}, - "start_hour_utc": {"required": True}, - } - - _attribute_map = { - "day_of_week": {"key": "dayOfWeek", "type": "str"}, - "start_hour_utc": {"key": "startHourUtc", "type": "int"}, - "maintenance_window": {"key": "maintenanceWindow", "type": "duration"}, - } - - def __init__( - self, - *, - day_of_week: Union[str, "_models.DayOfWeek"], - start_hour_utc: int, - maintenance_window: Optional[datetime.timedelta] = None, - **kwargs: Any - ) -> None: - """ - :keyword day_of_week: Day of the week when a cache can be patched. Required. Known values are: - "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Everyday", and - "Weekend". - :paramtype day_of_week: str or ~azure.mgmt.redis.models.DayOfWeek - :keyword start_hour_utc: Start hour after which cache patching can start. Required. - :paramtype start_hour_utc: int - :keyword maintenance_window: ISO8601 timespan specifying how much time cache patching can take. - :paramtype maintenance_window: ~datetime.timedelta - """ - super().__init__(**kwargs) - self.day_of_week = day_of_week - self.start_hour_utc = start_hour_utc - self.maintenance_window = maintenance_window - - -class Sku(_serialization.Model): - """SKU parameters supplied to the create Redis operation. - - All required parameters must be populated in order to send to server. - - :ivar name: The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium). - Required. Known values are: "Basic", "Standard", and "Premium". - :vartype name: str or ~azure.mgmt.redis.models.SkuName - :ivar family: The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium). - Required. Known values are: "C" and "P". - :vartype family: str or ~azure.mgmt.redis.models.SkuFamily - :ivar capacity: The size of the Redis cache to deploy. Valid values: for C (Basic/Standard) - family (0, 1, 2, 3, 4, 5, 6), for P (Premium) family (1, 2, 3, 4). Required. - :vartype capacity: int - """ - - _validation = { - "name": {"required": True}, - "family": {"required": True}, - "capacity": {"required": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "family": {"key": "family", "type": "str"}, - "capacity": {"key": "capacity", "type": "int"}, - } - - def __init__( - self, - *, - name: Union[str, "_models.SkuName"], - family: Union[str, "_models.SkuFamily"], - capacity: int, - **kwargs: Any - ) -> None: - """ - :keyword name: The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium). - Required. Known values are: "Basic", "Standard", and "Premium". - :paramtype name: str or ~azure.mgmt.redis.models.SkuName - :keyword family: The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = - Premium). Required. Known values are: "C" and "P". - :paramtype family: str or ~azure.mgmt.redis.models.SkuFamily - :keyword capacity: The size of the Redis cache to deploy. Valid values: for C (Basic/Standard) - family (0, 1, 2, 3, 4, 5, 6), for P (Premium) family (1, 2, 3, 4). Required. - :paramtype capacity: int - """ - super().__init__(**kwargs) - self.name = name - self.family = family - self.capacity = capacity - - -class UpgradeNotification(_serialization.Model): - """Properties of upgrade notification. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: Name of upgrade notification. - :vartype name: str - :ivar timestamp: Timestamp when upgrade notification occurred. - :vartype timestamp: ~datetime.datetime - :ivar upsell_notification: Details about this upgrade notification. - :vartype upsell_notification: dict[str, str] - """ - - _validation = { - "name": {"readonly": True}, - "timestamp": {"readonly": True}, - "upsell_notification": {"readonly": True}, - } - - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "timestamp": {"key": "timestamp", "type": "iso-8601"}, - "upsell_notification": {"key": "upsellNotification", "type": "{str}"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.name = None - self.timestamp = None - self.upsell_notification = None - - -class UserAssignedIdentity(_serialization.Model): - """User assigned identity properties. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar principal_id: The principal ID of the assigned identity. - :vartype principal_id: str - :ivar client_id: The client ID of the assigned identity. - :vartype client_id: str - """ - - _validation = { - "principal_id": {"readonly": True}, - "client_id": {"readonly": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "client_id": {"key": "clientId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.principal_id = None - self.client_id = None diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_patch.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_patch.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/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/redis/azure-mgmt-redis/azure/mgmt/redis/models/_redis_management_client_enums.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_redis_management_client_enums.py deleted file mode 100644 index e192fc22d960..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/models/_redis_management_client_enums.py +++ /dev/null @@ -1,187 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class AccessPolicyAssignmentProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Provisioning state of an access policy assignment set.""" - - UPDATING = "Updating" - SUCCEEDED = "Succeeded" - DELETING = "Deleting" - DELETED = "Deleted" - CANCELED = "Canceled" - FAILED = "Failed" - - -class AccessPolicyProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Provisioning state of access policy.""" - - UPDATING = "Updating" - SUCCEEDED = "Succeeded" - DELETING = "Deleting" - DELETED = "Deleted" - CANCELED = "Canceled" - FAILED = "Failed" - - -class AccessPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Built-In or Custom access policy.""" - - CUSTOM = "Custom" - BUILT_IN = "BuiltIn" - - -class DayOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Day of the week when a cache can be patched.""" - - MONDAY = "Monday" - TUESDAY = "Tuesday" - WEDNESDAY = "Wednesday" - THURSDAY = "Thursday" - FRIDAY = "Friday" - SATURDAY = "Saturday" - SUNDAY = "Sunday" - EVERYDAY = "Everyday" - WEEKEND = "Weekend" - - -class DefaultName(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """DefaultName.""" - - DEFAULT = "default" - - -class ManagedServiceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of managed service identity (where both SystemAssigned and UserAssigned types are - allowed). - """ - - NONE = "None" - SYSTEM_ASSIGNED = "SystemAssigned" - USER_ASSIGNED = "UserAssigned" - SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" - - -class PrivateEndpointConnectionProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The current provisioning state.""" - - SUCCEEDED = "Succeeded" - CREATING = "Creating" - DELETING = "Deleting" - FAILED = "Failed" - - -class PrivateEndpointServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The private endpoint connection status.""" - - PENDING = "Pending" - APPROVED = "Approved" - REJECTED = "Rejected" - - -class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Redis instance provisioning status.""" - - CREATING = "Creating" - DELETING = "Deleting" - DISABLED = "Disabled" - FAILED = "Failed" - LINKING = "Linking" - PROVISIONING = "Provisioning" - RECOVERING_SCALE_FAILURE = "RecoveringScaleFailure" - SCALING = "Scaling" - SUCCEEDED = "Succeeded" - UNLINKING = "Unlinking" - UNPROVISIONING = "Unprovisioning" - UPDATING = "Updating" - CONFIGURING_AAD = "ConfiguringAAD" - - -class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Whether or not public endpoint access is allowed for this cache. Value is optional but if - passed in, must be 'Enabled' or 'Disabled'. If 'Disabled', private endpoints are the exclusive - access method. Default value is 'Enabled'. - """ - - ENABLED = "Enabled" - DISABLED = "Disabled" - - -class RebootType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Which Redis node(s) to reboot. Depending on this value data loss is possible.""" - - PRIMARY_NODE = "PrimaryNode" - SECONDARY_NODE = "SecondaryNode" - ALL_NODES = "AllNodes" - - -class RedisKeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The Redis access key to regenerate.""" - - PRIMARY = "Primary" - SECONDARY = "Secondary" - - -class ReplicationRole(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Role of the linked server.""" - - PRIMARY = "Primary" - SECONDARY = "Secondary" - - -class SkuFamily(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium).""" - - C = "C" - P = "P" - - -class SkuName(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium).""" - - BASIC = "Basic" - STANDARD = "Standard" - PREMIUM = "Premium" - - -class TlsVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', - '1.1', '1.2'). - """ - - ONE0 = "1.0" - ONE1 = "1.1" - ONE2 = "1.2" - - -class UpdateChannel(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Optional: Specifies the update channel for the monthly Redis updates your Redis Cache will - receive. Caches using 'Preview' update channel get latest Redis updates at least 4 weeks ahead - of 'Stable' channel caches. Default value is 'Stable'. - """ - - STABLE = "Stable" - PREVIEW = "Preview" - - -class ZonalAllocationPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Optional: Specifies how availability zones are allocated to the Redis cache. 'Automatic' - enables zone redundancy and Azure will automatically select zones based on regional - availability and capacity. 'UserDefined' will select availability zones passed in by you using - the 'zones' parameter. 'NoZones' will produce a non-zonal cache. If 'zonalAllocationPolicy' is - not passed, it will be set to 'UserDefined' when zones are passed in, otherwise, it will be set - to 'Automatic' in regions where zones are supported and 'NoZones' in regions where zones are - not supported. - """ - - AUTOMATIC = "Automatic" - USER_DEFINED = "UserDefined" - NO_ZONES = "NoZones" diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/__init__.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/__init__.py index db28d1129b34..723f590f186c 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/__init__.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/__init__.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. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -13,15 +13,15 @@ from ._patch import * # pylint: disable=unused-wildcard-import from ._operations import Operations # type: ignore -from ._redis_operations import RedisOperations # type: ignore -from ._firewall_rules_operations import FirewallRulesOperations # type: ignore -from ._patch_schedules_operations import PatchSchedulesOperations # type: ignore -from ._linked_server_operations import LinkedServerOperations # type: ignore -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations # type: ignore -from ._private_link_resources_operations import PrivateLinkResourcesOperations # type: ignore -from ._async_operation_status_operations import AsyncOperationStatusOperations # type: ignore -from ._access_policy_operations import AccessPolicyOperations # type: ignore -from ._access_policy_assignment_operations import AccessPolicyAssignmentOperations # type: ignore +from ._operations import LinkedServerOperations # type: ignore +from ._operations import PrivateEndpointConnectionsOperations # type: ignore +from ._operations import RedisOperations # type: ignore +from ._operations import PrivateLinkResourcesOperations # type: ignore +from ._operations import FirewallRulesOperations # type: ignore +from ._operations import PatchSchedulesOperations # type: ignore +from ._operations import AccessPolicyOperations # type: ignore +from ._operations import AccessPolicyAssignmentOperations # type: ignore +from ._operations import AsyncOperationStatusOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -29,15 +29,15 @@ __all__ = [ "Operations", - "RedisOperations", - "FirewallRulesOperations", - "PatchSchedulesOperations", "LinkedServerOperations", "PrivateEndpointConnectionsOperations", + "RedisOperations", "PrivateLinkResourcesOperations", - "AsyncOperationStatusOperations", + "FirewallRulesOperations", + "PatchSchedulesOperations", "AccessPolicyOperations", "AccessPolicyAssignmentOperations", + "AsyncOperationStatusOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_access_policy_assignment_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_access_policy_assignment_operations.py deleted file mode 100644 index 3c0d691e9495..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_access_policy_assignment_operations.py +++ /dev/null @@ -1,700 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_update_request( - resource_group_name: str, cache_name: str, access_policy_assignment_name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments/{accessPolicyAssignmentName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "accessPolicyAssignmentName": _SERIALIZER.url( - "access_policy_assignment_name", - access_policy_assignment_name, - "str", - max_length=63, - min_length=3, - pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$", - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_delete_request( - resource_group_name: str, cache_name: str, access_policy_assignment_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments/{accessPolicyAssignmentName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "accessPolicyAssignmentName": _SERIALIZER.url( - "access_policy_assignment_name", - access_policy_assignment_name, - "str", - max_length=63, - min_length=3, - pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$", - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, cache_name: str, access_policy_assignment_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments/{accessPolicyAssignmentName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "accessPolicyAssignmentName": _SERIALIZER.url( - "access_policy_assignment_name", - access_policy_assignment_name, - "str", - max_length=63, - min_length=3, - pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$", - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_list_request(resource_group_name: str, cache_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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 AccessPolicyAssignmentOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`access_policy_assignment` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - def _create_update_initial( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: Union[_models.RedisCacheAccessPolicyAssignment, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisCacheAccessPolicyAssignment") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: _models.RedisCacheAccessPolicyAssignment, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisCacheAccessPolicyAssignment]: - """Adds the access policy assignment to the specified users. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. - Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment - :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 either RedisCacheAccessPolicyAssignment or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisCacheAccessPolicyAssignment]: - """Adds the access policy assignment to the specified users. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. - Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either RedisCacheAccessPolicyAssignment or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_assignment_name: str, - parameters: Union[_models.RedisCacheAccessPolicyAssignment, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.RedisCacheAccessPolicyAssignment]: - """Adds the access policy assignment to the specified users. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. - Is either a RedisCacheAccessPolicyAssignment type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment or IO[bytes] - :return: An instance of LROPoller that returns either RedisCacheAccessPolicyAssignment or the - result of cls(response) - :rtype: - ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = 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_update_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - 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): - deserialized = self._deserialize("RedisCacheAccessPolicyAssignment", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisCacheAccessPolicyAssignment].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.RedisCacheAccessPolicyAssignment]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial( - self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes the access policy assignment from a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get( - self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any - ) -> _models.RedisCacheAccessPolicyAssignment: - """Gets the list of assignments for an access policy of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_assignment_name: The name of the access policy assignment. Required. - :type access_policy_assignment_name: str - :return: RedisCacheAccessPolicyAssignment or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_assignment_name=access_policy_assignment_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisCacheAccessPolicyAssignment", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> Iterable["_models.RedisCacheAccessPolicyAssignment"]: - """Gets the list of access policy assignments associated with this redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisCacheAccessPolicyAssignment or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicyAssignmentList] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RedisCacheAccessPolicyAssignmentList", 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) - - _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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_access_policy_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_access_policy_operations.py deleted file mode 100644 index 52e6a847e3a3..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_access_policy_operations.py +++ /dev/null @@ -1,700 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_update_request( - resource_group_name: str, cache_name: str, access_policy_name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies/{accessPolicyName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "accessPolicyName": _SERIALIZER.url( - "access_policy_name", - access_policy_name, - "str", - max_length=63, - min_length=3, - pattern=r"^([a-zA-Z0-9][a-zA-Z0-9- ]*[a-zA-Z0-9]|[a-zA-Z0-9])$", - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_delete_request( - resource_group_name: str, cache_name: str, access_policy_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies/{accessPolicyName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "accessPolicyName": _SERIALIZER.url( - "access_policy_name", - access_policy_name, - "str", - max_length=63, - min_length=3, - pattern=r"^([a-zA-Z0-9][a-zA-Z0-9- ]*[a-zA-Z0-9]|[a-zA-Z0-9])$", - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, cache_name: str, access_policy_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies/{accessPolicyName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "accessPolicyName": _SERIALIZER.url( - "access_policy_name", - access_policy_name, - "str", - max_length=63, - min_length=3, - pattern=r"^([a-zA-Z0-9][a-zA-Z0-9- ]*[a-zA-Z0-9]|[a-zA-Z0-9])$", - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_list_request(resource_group_name: str, cache_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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 AccessPolicyOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`access_policy` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - def _create_update_initial( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: Union[_models.RedisCacheAccessPolicy, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisCacheAccessPolicy") - - _request = build_create_update_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: _models.RedisCacheAccessPolicy, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisCacheAccessPolicy]: - """Adds an access policy to the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy - :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 either RedisCacheAccessPolicy or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisCacheAccessPolicy]: - """Adds an access policy to the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either RedisCacheAccessPolicy or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create_update( - self, - resource_group_name: str, - cache_name: str, - access_policy_name: str, - parameters: Union[_models.RedisCacheAccessPolicy, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.RedisCacheAccessPolicy]: - """Adds an access policy to the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :param parameters: Parameters supplied to the Create Update Access Policy operation. Is either - a RedisCacheAccessPolicy type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy or IO[bytes] - :return: An instance of LROPoller that returns either RedisCacheAccessPolicy or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisCacheAccessPolicy] = 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_update_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - 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): - deserialized = self._deserialize("RedisCacheAccessPolicy", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisCacheAccessPolicy].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.RedisCacheAccessPolicy]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial( - self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes the access policy from a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get( - self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any - ) -> _models.RedisCacheAccessPolicy: - """Gets the detailed information about an access policy of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param access_policy_name: The name of the access policy that is being added to the Redis - cache. Required. - :type access_policy_name: str - :return: RedisCacheAccessPolicy or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicy - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicy] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - access_policy_name=access_policy_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisCacheAccessPolicy", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> Iterable["_models.RedisCacheAccessPolicy"]: - """Gets the list of access policies associated with this redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisCacheAccessPolicy or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicy] - :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", self._config.api_version)) - cls: ClsType[_models.RedisCacheAccessPolicyList] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RedisCacheAccessPolicyList", 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) - - _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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_async_operation_status_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_async_operation_status_operations.py deleted file mode 100644 index c16eb9cb45dc..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_async_operation_status_operations.py +++ /dev/null @@ -1,140 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.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 .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -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(location: str, operation_id: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.Cache/locations/{location}/asyncOperations/{operationId}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "location": _SERIALIZER.url("location", location, "str"), - "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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 AsyncOperationStatusOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`async_operation_status` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, location: str, operation_id: str, **kwargs: Any) -> _models.OperationStatus: - """For checking the ongoing status of an operation. - - :param location: The location at which operation was triggered. Required. - :type location: str - :param operation_id: The ID of asynchronous operation. Required. - :type operation_id: str - :return: OperationStatus or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.OperationStatus - :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", self._config.api_version)) - cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) - - _request = build_get_request( - location=location, - operation_id=operation_id, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("OperationStatus", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_firewall_rules_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_firewall_rules_operations.py deleted file mode 100644 index ad343c9e8776..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_firewall_rules_operations.py +++ /dev/null @@ -1,546 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.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 .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(resource_group_name: str, cache_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - } - - _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_create_or_update_request( - resource_group_name: str, cache_name: str, rule_name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules/{ruleName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_get_request( - resource_group_name: str, cache_name: str, rule_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules/{ruleName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_delete_request( - resource_group_name: str, cache_name: str, rule_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules/{ruleName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class FirewallRulesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`firewall_rules` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, resource_group_name: str, cache_name: str, **kwargs: Any) -> Iterable["_models.RedisFirewallRule"]: - """Gets all firewall rules in the specified redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisFirewallRule or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisFirewallRule] - :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", self._config.api_version)) - cls: ClsType[_models.RedisFirewallRuleListResult] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RedisFirewallRuleListResult", 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) - - _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 = 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) - - @overload - def create_or_update( - self, - resource_group_name: str, - cache_name: str, - rule_name: str, - parameters: _models.RedisFirewallRule, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisFirewallRule: - """Create or update a redis cache firewall rule. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :param parameters: Parameters supplied to the create or update redis firewall rule operation. - Required. - :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - cache_name: str, - rule_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisFirewallRule: - """Create or update a redis cache firewall rule. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :param parameters: Parameters supplied to the create or update redis firewall rule operation. - Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - resource_group_name: str, - cache_name: str, - rule_name: str, - parameters: Union[_models.RedisFirewallRule, IO[bytes]], - **kwargs: Any - ) -> _models.RedisFirewallRule: - """Create or update a redis cache firewall rule. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :param parameters: Parameters supplied to the create or update redis firewall rule operation. - Is either a RedisFirewallRule type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule or IO[bytes] - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisFirewallRule] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisFirewallRule") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - rule_name=rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisFirewallRule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get( - self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any - ) -> _models.RedisFirewallRule: - """Gets a single firewall rule in a specified redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :return: RedisFirewallRule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisFirewallRule - :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", self._config.api_version)) - cls: ClsType[_models.RedisFirewallRule] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - rule_name=rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisFirewallRule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any - ) -> None: - """Deletes a single firewall rule in a specified redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param rule_name: The name of the firewall rule. Required. - :type rule_name: str - :return: None or the result of cls(response) - :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", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - rule_name=rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_linked_server_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_linked_server_operations.py deleted file mode 100644 index 3aadfa6f9841..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_linked_server_operations.py +++ /dev/null @@ -1,668 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request( - resource_group_name: str, name: str, linked_server_name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "linkedServerName": _SERIALIZER.url("linked_server_name", linked_server_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_delete_request( - resource_group_name: str, name: str, linked_server_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "linkedServerName": _SERIALIZER.url("linked_server_name", linked_server_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, name: str, linked_server_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "linkedServerName": _SERIALIZER.url("linked_server_name", linked_server_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_list_request(resource_group_name: str, name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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 LinkedServerOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`linked_server` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - def _create_initial( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: Union[_models.RedisLinkedServerCreateParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisLinkedServerCreateParameters") - - _request = build_create_request( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: _models.RedisLinkedServerCreateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisLinkedServerWithProperties]: - """Adds a linked server to the Redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :param parameters: Parameters supplied to the Create Linked server operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters - :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 either RedisLinkedServerWithProperties or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisLinkedServerWithProperties]: - """Adds a linked server to the Redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :param parameters: Parameters supplied to the Create Linked server operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either RedisLinkedServerWithProperties or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create( - self, - resource_group_name: str, - name: str, - linked_server_name: str, - parameters: Union[_models.RedisLinkedServerCreateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.RedisLinkedServerWithProperties]: - """Adds a linked server to the Redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :param parameters: Parameters supplied to the Create Linked server operation. Is either a - RedisLinkedServerCreateParameters type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters or IO[bytes] - :return: An instance of LROPoller that returns either RedisLinkedServerWithProperties or the - result of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisLinkedServerWithProperties] = 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_initial( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - 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): - deserialized = self._deserialize("RedisLinkedServerWithProperties", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisLinkedServerWithProperties].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.RedisLinkedServerWithProperties]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial( - self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - if response.status_code == 202: - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes the linked server from a redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server that is being added to the Redis - cache. Required. - :type linked_server_name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get( - self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any - ) -> _models.RedisLinkedServerWithProperties: - """Gets the detailed information about a linked server of a redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param linked_server_name: The name of the linked server. Required. - :type linked_server_name: str - :return: RedisLinkedServerWithProperties or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisLinkedServerWithProperties - :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", self._config.api_version)) - cls: ClsType[_models.RedisLinkedServerWithProperties] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - name=name, - linked_server_name=linked_server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisLinkedServerWithProperties", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, resource_group_name: str, name: str, **kwargs: Any - ) -> Iterable["_models.RedisLinkedServerWithProperties"]: - """Gets the list of linked servers associated with this redis cache (requires Premium SKU). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :return: An iterator like instance of either RedisLinkedServerWithProperties or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] - :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", self._config.api_version)) - cls: ClsType[_models.RedisLinkedServerWithPropertiesList] = 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_list_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RedisLinkedServerWithPropertiesList", 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) - - _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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_operations.py index fe8f3c3370c3..c6f7e2a47882 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_operations.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_operations.py @@ -1,52 +1,1198 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models -from .._serialization import Serializer +from .._configuration import RedisManagementClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request(**kwargs: Any) -> HttpRequest: +def build_operations_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/providers/Microsoft.Cache/operations") + _url = "/providers/Microsoft.Cache/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_linked_server_get_request( + resource_group_name: str, name: str, linked_server_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "linkedServerName": _SERIALIZER.url("linked_server_name", linked_server_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_linked_server_create_request( + resource_group_name: str, name: str, linked_server_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "linkedServerName": _SERIALIZER.url("linked_server_name", linked_server_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_linked_server_delete_request( + resource_group_name: str, name: str, linked_server_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers/{linkedServerName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "linkedServerName": _SERIALIZER.url("linked_server_name", linked_server_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_linked_server_list_request( + resource_group_name: str, name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/linkedServers" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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_private_endpoint_connections_get_request( # pylint: disable=name-too-long + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections/{privateEndpointConnectionName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_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_private_endpoint_connections_put_request( # pylint: disable=name-too-long + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections/{privateEndpointConnectionName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_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_private_endpoint_connections_delete_request( # pylint: disable=name-too-long + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections/{privateEndpointConnectionName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_private_endpoint_connections_list_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_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_redis_get_request(resource_group_name: str, name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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_redis_create_request(resource_group_name: str, name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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_redis_update_request(resource_group_name: str, name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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_redis_delete_request(resource_group_name: str, name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_redis_list_by_resource_group_request( # pylint: disable=name-too-long + resource_group_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_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_redis_list_by_subscription_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: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Cache/redis" + 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) + + +def build_redis_list_upgrade_notifications_request( # pylint: disable=name-too-long + resource_group_name: str, name: str, subscription_id: str, *, history: float, **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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/listUpgradeNotifications" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["history"] = _SERIALIZER.query("history", history, "float") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redis_list_keys_request( + resource_group_name: str, name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/listKeys" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redis_regenerate_key_request( + resource_group_name: str, name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/regenerateKey" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redis_force_reboot_request( + resource_group_name: str, name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/forceReboot" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redis_import_data_request( + resource_group_name: str, name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/import" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redis_export_data_request( + resource_group_name: str, name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/export" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", 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") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redis_flush_cache_request( + resource_group_name: str, cache_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/flush" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_redis_check_name_availability_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 {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Cache/checkNameAvailability" + 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 + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_private_link_resources_list_by_redis_cache_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateLinkResources" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_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_firewall_rules_get_request( + resource_group_name: str, cache_name: str, rule_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules/{ruleName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_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_firewall_rules_create_or_update_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, rule_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules/{ruleName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_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_firewall_rules_delete_request( + resource_group_name: str, cache_name: str, rule_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules/{ruleName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_firewall_rules_list_request( + resource_group_name: str, cache_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_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_patch_schedules_get_request( + resource_group_name: str, name: str, default: Union[str, _models.DefaultName], 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/patchSchedules/{default}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "default": _SERIALIZER.url("default", default, "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_patch_schedules_create_or_update_request( # pylint: disable=name-too-long + resource_group_name: str, name: str, default: Union[str, _models.DefaultName], subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/patchSchedules/{default}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "default": _SERIALIZER.url("default", default, "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_patch_schedules_delete_request( + resource_group_name: str, name: str, default: Union[str, _models.DefaultName], subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/patchSchedules/{default}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "default": _SERIALIZER.url("default", default, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_patch_schedules_list_by_redis_resource_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/patchSchedules" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_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_access_policy_get_request( + resource_group_name: str, cache_name: str, access_policy_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies/{accessPolicyName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "accessPolicyName": _SERIALIZER.url("access_policy_name", access_policy_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_access_policy_create_update_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, access_policy_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies/{accessPolicyName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "accessPolicyName": _SERIALIZER.url("access_policy_name", access_policy_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_access_policy_delete_request( + resource_group_name: str, cache_name: str, access_policy_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies/{accessPolicyName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "accessPolicyName": _SERIALIZER.url("access_policy_name", access_policy_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_access_policy_list_request( + resource_group_name: str, cache_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicies" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_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_access_policy_assignment_get_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, access_policy_assignment_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments/{accessPolicyAssignmentName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "accessPolicyAssignmentName": _SERIALIZER.url( + "access_policy_assignment_name", access_policy_assignment_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_access_policy_assignment_create_update_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, access_policy_assignment_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments/{accessPolicyAssignmentName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "accessPolicyAssignmentName": _SERIALIZER.url( + "access_policy_assignment_name", access_policy_assignment_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_access_policy_assignment_delete_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, access_policy_assignment_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-08-01-preview")) + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments/{accessPolicyAssignmentName}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_name, "str"), + "accessPolicyAssignmentName": _SERIALIZER.url( + "access_policy_assignment_name", access_policy_assignment_name, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_access_policy_assignment_list_request( # pylint: disable=name-too-long + resource_group_name: str, cache_name: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/accessPolicyAssignments" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "cacheName": _SERIALIZER.url("cache_name", cache_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_async_operation_status_get_request( + location: str, operation_id: str, 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", "2025-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = ( + "/subscriptions/{subscriptionId}/providers/Microsoft.Cache/locations/{location}/asyncOperations/{operationId}" + ) + path_format_arguments = { + "location": _SERIALIZER.url("location", location, "str"), + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + "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") @@ -64,31 +1210,5345 @@ class Operations: Instead, you should access the following operations through :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`operations` attribute. + :attr:`operations` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: + """List the operations for the provider. + + :return: An iterator like instance of Operation + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Operation]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_operations_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Operation], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class LinkedServerOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`linked_server` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any + ) -> _models.RedisLinkedServerWithProperties: + """Gets the detailed information about a linked server of a redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :return: RedisLinkedServerWithProperties. The RedisLinkedServerWithProperties is compatible + with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisLinkedServerWithProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisLinkedServerWithProperties] = kwargs.pop("cls", None) + + _request = build_linked_server_get_request( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisLinkedServerWithProperties, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_initial( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: Union[_models.RedisLinkedServerCreateParameters, 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 = kwargs.pop("params", {}) or {} + + 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_linked_server_create_request( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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")) + + 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( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: _models.RedisLinkedServerCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters + :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 RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + name: str, + linked_server_name: str, + parameters: Union[_models.RedisLinkedServerCreateParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.RedisLinkedServerWithProperties]: + """Adds a linked server to the Redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :param parameters: Parameters supplied to the Create Linked server operation. Is one of the + following types: RedisLinkedServerCreateParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisLinkedServerCreateParameters or JSON or + IO[bytes] + :return: An instance of LROPoller that returns RedisLinkedServerWithProperties. The + RedisLinkedServerWithProperties is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisLinkedServerWithProperties] = 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_initial( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + parameters=parameters, + 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.RedisLinkedServerWithProperties, 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.RedisLinkedServerWithProperties].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.RedisLinkedServerWithProperties]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( + self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_linked_server_delete_request( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace + def begin_delete( + self, resource_group_name: str, name: str, linked_server_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the linked server from a redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param linked_server_name: The name of the RedisLinkedServerWithProperties. Required. + :type linked_server_name: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + name=name, + linked_server_name=linked_server_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, name: str, **kwargs: Any + ) -> ItemPaged["_models.RedisLinkedServerWithProperties"]: + """Gets the list of linked servers associated with this redis cache (requires Premium SKU). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :return: An iterator like instance of RedisLinkedServerWithProperties + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisLinkedServerWithProperties] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisLinkedServerWithProperties]] = 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_linked_server_list_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisLinkedServerWithProperties], + 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 PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`private_endpoint_connections` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Gets the specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: PrivateEndpointConnection. The PrivateEndpointConnection is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + _request = build_private_endpoint_connections_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PrivateEndpointConnection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _put_initial( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: Union[_models.PrivateEndpointConnection, 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 = kwargs.pop("params", {}) or {} + + 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(properties, (IOBase, bytes)): + _content = properties + else: + _content = json.dumps(properties, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_private_endpoint_connections_put_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Required. + :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection + :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 PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Required. + :type properties: 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 PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Required. + :type properties: 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 PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_put( + self, + resource_group_name: str, + cache_name: str, + private_endpoint_connection_name: str, + properties: Union[_models.PrivateEndpointConnection, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the state of specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :param properties: The private endpoint connection properties. Is one of the following types: + PrivateEndpointConnection, JSON, IO[bytes] Required. + :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection or JSON or IO[bytes] + :return: An instance of LROPoller that returns PrivateEndpointConnection. The + PrivateEndpointConnection is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = 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._put_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + properties=properties, + 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.PrivateEndpointConnection, 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.PrivateEndpointConnection].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> None: + """Deletes the specified private endpoint connection associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection associated + with the Azure resource. Required. + :type private_endpoint_connection_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_private_endpoint_connections_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> ItemPaged["_models.PrivateEndpointConnection"]: + """List all the private endpoint connections associated with the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of PrivateEndpointConnection + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PrivateEndpointConnection]] = 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_private_endpoint_connections_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.PrivateEndpointConnection], + 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 RedisOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`redis` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisResource: + """Gets a Redis cache (resource description). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :return: RedisResource. The RedisResource is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisResource] = kwargs.pop("cls", None) + + _request = build_redis_get_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisResource, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisCreateParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_create_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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")) + + 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( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisCreateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters + :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 RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisCreateParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Create Redis operation. Is one of the following + types: RedisCreateParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters or JSON or IO[bytes] + :return: An instance of LROPoller that returns RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisResource] = 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_initial( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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.RedisResource, 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.RedisResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.RedisResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _update_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisUpdateParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_update_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_update( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters + :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 RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisUpdateParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.RedisResource]: + """Update an existing Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters supplied to the Update Redis operation. Is one of the following + types: RedisUpdateParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters or JSON or IO[bytes] + :return: An instance of LROPoller that returns RedisResource. The RedisResource is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisResource] = 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( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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.RedisResource, 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.RedisResource].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.RedisResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial(self, resource_group_name: str, name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_redis_delete_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace + def begin_delete(self, resource_group_name: str, name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes a Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + name=name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> ItemPaged["_models.RedisResource"]: + """Lists all Redis caches in a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of RedisResource + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisResource]] = 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_redis_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_subscription(self, **kwargs: Any) -> ItemPaged["_models.RedisResource"]: + """Gets all Redis caches in the specified subscription. + + :return: An iterator like instance of RedisResource + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisResource]] = 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_redis_list_by_subscription_request( + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisResource], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_upgrade_notifications( + self, resource_group_name: str, name: str, *, history: float, **kwargs: Any + ) -> ItemPaged["_models.UpgradeNotification"]: + """[Deprecated] Gets any upgrade notifications for a Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :keyword history: how many minutes in past to look for upgrade notifications. Required. + :paramtype history: float + :return: An iterator like instance of UpgradeNotification + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.UpgradeNotification] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.UpgradeNotification]] = 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_redis_list_upgrade_notifications_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + history=history, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.UpgradeNotification], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_keys(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisAccessKeys: + """Retrieve a Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :return: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisAccessKeys] = kwargs.pop("cls", None) + + _request = build_redis_list_keys_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisAccessKeys, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisRegenerateKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. Required. + :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. 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: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. 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: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def regenerate_key( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisRegenerateKeyParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisAccessKeys: + """Regenerate Redis cache's access keys. This operation requires write permission to the cache + resource. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which key to regenerate. Is one of the following types: + RedisRegenerateKeyParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters or JSON or IO[bytes] + :return: RedisAccessKeys. The RedisAccessKeys is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisAccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisAccessKeys] = 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_redis_regenerate_key_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisAccessKeys, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: _models.RedisRebootParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. Required. + :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. 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: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. 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: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def force_reboot( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.RedisRebootParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisForceRebootResponse: + """Reboot specified Redis node(s). This operation requires write permission to the cache resource. + There can be potential data loss. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Specifies which Redis node(s) to reboot. Is one of the following types: + RedisRebootParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters or JSON or IO[bytes] + :return: RedisForceRebootResponse. The RedisForceRebootResponse is compatible with + MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisForceRebootResponse] = 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_redis_force_reboot_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisForceRebootResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _import_data_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ImportRDBParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_import_data_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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_import_data( + self, + resource_group_name: str, + name: str, + parameters: _models.ImportRDBParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Required. + :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters + :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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_import_data( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_import_data( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_import_data( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ImportRDBParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[None]: + """Import data into Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis import operation. Is one of the following types: + ImportRDBParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters or JSON or IO[bytes] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = 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._import_data_initial( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _export_data_initial( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ExportRDBParameters, 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 = kwargs.pop("params", {}) or {} + + 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_redis_export_data_request( + resource_group_name=resource_group_name, + name=name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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_export_data( + self, + resource_group_name: str, + name: str, + parameters: _models.ExportRDBParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Required. + :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters + :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 None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_export_data( + self, + resource_group_name: str, + name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_export_data( + self, + resource_group_name: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_export_data( + self, + resource_group_name: str, + name: str, + parameters: Union[_models.ExportRDBParameters, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[None]: + """Export data from the redis cache to blobs in a container. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the RedisResource. Required. + :type name: str + :param parameters: Parameters for Redis export operation. Is one of the following types: + ExportRDBParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters or JSON or IO[bytes] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = 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._export_data_initial( + resource_group_name=resource_group_name, + name=name, + parameters=parameters, + 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): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + def _flush_cache_initial(self, resource_group_name: str, cache_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_redis_flush_cache_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def begin_flush_cache( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatusResult]: + """Deletes all of the keys in a cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An instance of LROPoller that returns OperationStatusResult. The OperationStatusResult + is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.OperationStatusResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationStatusResult] = 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._flush_cache_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + deserialized = _deserialize(_models.OperationStatusResult, 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.OperationStatusResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.OperationStatusResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + def check_name_availability( + self, + parameters: _models.CheckNameAvailabilityParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. Required. + :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. 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: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. 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: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( # pylint: disable=inconsistent-return-statements + self, parameters: Union[_models.CheckNameAvailabilityParameters, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Checks that the redis cache name is valid and is not already in use. + + :param parameters: The request body. Is one of the following types: + CheckNameAvailabilityParameters, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters or JSON or IO[bytes] + :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 = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = 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_redis_check_name_availability_request( + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`private_link_resources` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_redis_cache( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> ItemPaged["_models.PrivateLinkResource"]: + """Gets the private link resources that need to be created for a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of PrivateLinkResource + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PrivateLinkResource]] = 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_private_link_resources_list_by_redis_cache_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.PrivateLinkResource], + 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 FirewallRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`firewall_rules` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any + ) -> _models.RedisFirewallRule: + """Gets a single firewall rule in a specified redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisFirewallRule] = kwargs.pop("cls", None) + + _request = build_firewall_rules_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + rule_name=rule_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisFirewallRule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: _models.RedisFirewallRule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Required. + :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + cache_name: str, + rule_name: str, + parameters: Union[_models.RedisFirewallRule, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisFirewallRule: + """Create or update a redis cache firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :param parameters: Parameters supplied to the create or update redis firewall rule operation. + Is one of the following types: RedisFirewallRule, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisFirewallRule or JSON or IO[bytes] + :return: RedisFirewallRule. The RedisFirewallRule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisFirewallRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisFirewallRule] = 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_firewall_rules_create_or_update_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + rule_name=rule_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisFirewallRule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, cache_name: str, rule_name: str, **kwargs: Any + ) -> None: + """Deletes a single firewall rule in a specified redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param rule_name: The name of the firewall rule. Required. + :type rule_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_firewall_rules_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + rule_name=rule_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list(self, resource_group_name: str, cache_name: str, **kwargs: Any) -> ItemPaged["_models.RedisFirewallRule"]: + """Gets all firewall rules in the specified redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisFirewallRule + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisFirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisFirewallRule]] = 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_firewall_rules_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisFirewallRule], + 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 PatchSchedulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`patch_schedules` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Gets the patching schedule of a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :return: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisPatchSchedule] = kwargs.pop("cls", None) + + _request = build_patch_schedules_get_request( + resource_group_name=resource_group_name, + name=name, + default=default, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisPatchSchedule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: _models.RedisPatchSchedule, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. Required. + :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. 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: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. 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: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, + resource_group_name: str, + name: str, + default: Union[str, _models.DefaultName], + parameters: Union[_models.RedisPatchSchedule, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.RedisPatchSchedule: + """Create or replace the patching schedule for Redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :param parameters: Parameters to set the patching schedule for Redis cache. Is one of the + following types: RedisPatchSchedule, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule or JSON or IO[bytes] + :return: RedisPatchSchedule. The RedisPatchSchedule is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisPatchSchedule] = 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_patch_schedules_create_or_update_request( + resource_group_name=resource_group_name, + name=name, + default=default, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisPatchSchedule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any + ) -> None: + """Deletes the patching schedule of a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param name: The name of the redis cache. Required. + :type name: str + :param default: The name of the RedisPatchSchedule. "default" Required. + :type default: str or ~azure.mgmt.redis.models.DefaultName + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_patch_schedules_delete_request( + resource_group_name=resource_group_name, + name=name, + default=default, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def list_by_redis_resource( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> ItemPaged["_models.RedisPatchSchedule"]: + """Gets all patch schedules in the specified redis cache (there is only one). + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisPatchSchedule + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisPatchSchedule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisPatchSchedule]] = 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_patch_schedules_list_by_redis_resource_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisPatchSchedule], + 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 AccessPolicyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`access_policy` 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: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get( + self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any + ) -> _models.RedisCacheAccessPolicy: + """Gets the detailed information about an access policy of a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :return: RedisCacheAccessPolicy. The RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisCacheAccessPolicy] = kwargs.pop("cls", None) + + _request = build_access_policy_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisCacheAccessPolicy, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_initial( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: Union[_models.RedisCacheAccessPolicy, 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 = kwargs.pop("params", {}) or {} + + 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_access_policy_create_update_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: _models.RedisCacheAccessPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy + :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 RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_name: str, + parameters: Union[_models.RedisCacheAccessPolicy, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicy]: + """Adds an access policy to the redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :param parameters: Parameters supplied to the Create Update Access Policy operation. Is one of + the following types: RedisCacheAccessPolicy, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicy or JSON or IO[bytes] + :return: An instance of LROPoller that returns RedisCacheAccessPolicy. The + RedisCacheAccessPolicy is compatible with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisCacheAccessPolicy] = 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_update_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + parameters=parameters, + 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.RedisCacheAccessPolicy, 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.RedisCacheAccessPolicy].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.RedisCacheAccessPolicy]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( + self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_access_policy_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace + def begin_delete( + self, resource_group_name: str, cache_name: str, access_policy_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the access policy from a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_name: The name of the access policy that is being added to the Redis + cache. Required. + :type access_policy_name: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_name=access_policy_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> ItemPaged["_models.RedisCacheAccessPolicy"]: + """Gets the list of access policies associated with this redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisCacheAccessPolicy + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedisCacheAccessPolicy]] = 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_access_policy_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisCacheAccessPolicy], + 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 AccessPolicyAssignmentOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`access_policy_assignment` attribute. """ - models = _models - - def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RedisManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: - """Lists all of the available REST API operations of the Microsoft.Cache provider. + def get( + self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any + ) -> _models.RedisCacheAccessPolicyAssignment: + """Gets the list of assignments for an access policy of a redis cache. - :return: An iterator like instance of either Operation or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.Operation] + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :return: RedisCacheAccessPolicyAssignment. The RedisCacheAccessPolicyAssignment is compatible + with MutableMapping + :rtype: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = kwargs.pop("cls", None) + + _request = build_access_policy_assignment_get_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedisCacheAccessPolicyAssignment, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def _create_update_initial( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: Union[_models.RedisCacheAccessPolicyAssignment, 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 = kwargs.pop("params", {}) or {} + + 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_access_policy_assignment_create_update_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + subscription_id=self._config.subscription_id, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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.ErrorResponse, + 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_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: _models.RedisCacheAccessPolicyAssignment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment + :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 RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Required. + :type parameters: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_update( + self, + resource_group_name: str, + cache_name: str, + access_policy_assignment_name: str, + parameters: Union[_models.RedisCacheAccessPolicyAssignment, JSON, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.RedisCacheAccessPolicyAssignment]: + """Adds the access policy assignment to the specified users. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :param parameters: Parameters supplied to the Create Update Access Policy Assignment operation. + Is one of the following types: RedisCacheAccessPolicyAssignment, JSON, IO[bytes] Required. + :type parameters: ~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment or JSON or + IO[bytes] + :return: An instance of LROPoller that returns RedisCacheAccessPolicyAssignment. The + RedisCacheAccessPolicyAssignment is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RedisCacheAccessPolicyAssignment] = 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_update_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + parameters=parameters, + 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.RedisCacheAccessPolicyAssignment, 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.RedisCacheAccessPolicyAssignment].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.RedisCacheAccessPolicyAssignment]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial( + self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_access_policy_assignment_delete_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = 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, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + response_headers = {} + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + 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 + + @distributed_trace + def begin_delete( + self, resource_group_name: str, cache_name: str, access_policy_assignment_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Deletes the access policy assignment from a redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :param access_policy_assignment_name: The name of the access policy assignment. Required. + :type access_policy_assignment_name: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = 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._delete_initial( + resource_group_name=resource_group_name, + cache_name=cache_name, + access_policy_assignment_name=access_policy_assignment_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace + def list( + self, resource_group_name: str, cache_name: str, **kwargs: Any + ) -> ItemPaged["_models.RedisCacheAccessPolicyAssignment"]: + """Gets the list of access policy assignments associated with this redis cache. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param cache_name: The name of the Redis cache. Required. + :type cache_name: str + :return: An iterator like instance of RedisCacheAccessPolicyAssignment + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisCacheAccessPolicyAssignment] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + _params = kwargs.pop("params", {}) or {} - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + cls: ClsType[List[_models.RedisCacheAccessPolicyAssignment]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -101,12 +6561,20 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - _request = build_list_request( - api_version=api_version, + _request = build_access_policy_assignment_list_request( + resource_group_name=resource_group_name, + cache_name=cache_name, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, headers=_headers, params=_params, ) - _request.url = self._client.format_url(_request.url) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -119,18 +6587,29 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.base_url", self._config.base_url, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("OperationListResult", pipeline_response) - list_of_elem = deserialized.value + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedisCacheAccessPolicyAssignment], + deserialized.get("value", []), + ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("nextLink") or None, iter(list_of_elem) def get_next(next_link=None): _request = prepare_request(next_link) @@ -143,9 +6622,99 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) + + +class AsyncOperationStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.redis.RedisManagementClient`'s + :attr:`async_operation_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: RedisManagementClientConfiguration = 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, location: str, operation_id: str, **kwargs: Any) -> _models.OperationStatus: + """For checking the ongoing status of an operation. + + :param location: The location at which operation was triggered. Required. + :type location: str + :param operation_id: The ID of asynchronous operation. Required. + :type operation_id: str + :return: OperationStatus. The OperationStatus is compatible with MutableMapping + :rtype: ~azure.mgmt.redis.models.OperationStatus + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) + + _request = build_async_operation_status_get_request( + location=location, + operation_id=operation_id, + subscription_id=self._config.subscription_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.OperationStatus, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_patch.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_patch.py +++ b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/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/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_patch_schedules_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_patch_schedules_operations.py deleted file mode 100644 index 19b6f0b65754..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_patch_schedules_operations.py +++ /dev/null @@ -1,547 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.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 .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_redis_resource_request( - resource_group_name: str, cache_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/patchSchedules", - ) # pylint: disable=line-too-long - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - } - - _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_create_or_update_request( - resource_group_name: str, name: str, default: Union[str, _models.DefaultName], 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/patchSchedules/{default}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "default": _SERIALIZER.url("default", default, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_delete_request( - resource_group_name: str, name: str, default: Union[str, _models.DefaultName], 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/patchSchedules/{default}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "default": _SERIALIZER.url("default", default, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, name: str, default: Union[str, _models.DefaultName], 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/patchSchedules/{default}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "default": _SERIALIZER.url("default", default, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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 PatchSchedulesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`patch_schedules` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_redis_resource( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> Iterable["_models.RedisPatchSchedule"]: - """Gets all patch schedules in the specified redis cache (there is only one). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisPatchSchedule] - :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", self._config.api_version)) - cls: ClsType[_models.RedisPatchScheduleListResult] = 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_list_by_redis_resource_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RedisPatchScheduleListResult", 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) - - _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 = 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) - - @overload - def create_or_update( - self, - resource_group_name: str, - name: str, - default: Union[str, _models.DefaultName], - parameters: _models.RedisPatchSchedule, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Create or replace the patching schedule for Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :param parameters: Parameters to set the patching schedule for Redis cache. Required. - :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - name: str, - default: Union[str, _models.DefaultName], - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Create or replace the patching schedule for Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :param parameters: Parameters to set the patching schedule for Redis cache. 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: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - resource_group_name: str, - name: str, - default: Union[str, _models.DefaultName], - parameters: Union[_models.RedisPatchSchedule, IO[bytes]], - **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Create or replace the patching schedule for Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :param parameters: Parameters to set the patching schedule for Redis cache. Is either a - RedisPatchSchedule type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisPatchSchedule or IO[bytes] - :return: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisPatchSchedule] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisPatchSchedule") - - _request = build_create_or_update_request( - resource_group_name=resource_group_name, - name=name, - default=default, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisPatchSchedule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any - ) -> None: - """Deletes the patching schedule of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :return: None or the result of cls(response) - :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", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - name=name, - default=default, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get( - self, resource_group_name: str, name: str, default: Union[str, _models.DefaultName], **kwargs: Any - ) -> _models.RedisPatchSchedule: - """Gets the patching schedule of a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the redis cache. Required. - :type name: str - :param default: Default string modeled as parameter for auto generation to work correctly. - "default" Required. - :type default: str or ~azure.mgmt.redis.models.DefaultName - :return: RedisPatchSchedule or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisPatchSchedule - :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", self._config.api_version)) - cls: ClsType[_models.RedisPatchSchedule] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - name=name, - default=default, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisPatchSchedule", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_private_endpoint_connections_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_private_endpoint_connections_operations.py deleted file mode 100644 index d4deb4a3a388..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_private_endpoint_connections_operations.py +++ /dev/null @@ -1,638 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(resource_group_name: str, cache_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_get_request( - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_name, "str" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_put_request( - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_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_delete_request( - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class PrivateEndpointConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`private_endpoint_connections` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> Iterable["_models.PrivateEndpointConnection"]: - """List all the private endpoint connections associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either PrivateEndpointConnection or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.PrivateEndpointConnection] - :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", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnectionListResult] = 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_list_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return 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 = 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) - - @distributed_trace - def get( - self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Gets the specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.PrivateEndpointConnection - :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", self._config.api_version)) - cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _put_initial( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(properties, (IOBase, bytes)): - _content = properties - else: - _json = self._serialize.body(properties, "PrivateEndpointConnection") - - _request = build_put_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_put( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: _models.PrivateEndpointConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PrivateEndpointConnection]: - """Update the state of specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :param properties: The private endpoint connection properties. Required. - :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection - :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 either PrivateEndpointConnection or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_put( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.PrivateEndpointConnection]: - """Update the state of specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :param properties: The private endpoint connection properties. Required. - :type properties: 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 either PrivateEndpointConnection or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_put( - self, - resource_group_name: str, - cache_name: str, - private_endpoint_connection_name: str, - properties: Union[_models.PrivateEndpointConnection, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.PrivateEndpointConnection]: - """Update the state of specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :param properties: The private endpoint connection properties. Is either a - PrivateEndpointConnection type or a IO[bytes] type. Required. - :type properties: ~azure.mgmt.redis.models.PrivateEndpointConnection or IO[bytes] - :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result - of cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.PrivateEndpointConnection] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PrivateEndpointConnection] = 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._put_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - properties=properties, - 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): - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.PrivateEndpointConnection].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.PrivateEndpointConnection]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, cache_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - """Deletes the specified private endpoint connection associated with the redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection associated - with the Azure resource. Required. - :type private_endpoint_connection_name: str - :return: None or the result of cls(response) - :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", self._config.api_version)) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - private_endpoint_connection_name=private_endpoint_connection_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_private_link_resources_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_private_link_resources_operations.py deleted file mode 100644 index 0b9fcebd60fb..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_private_link_resources_operations.py +++ /dev/null @@ -1,177 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -import urllib.parse - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.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 .. import models as _models -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_by_redis_cache_request( - resource_group_name: str, cache_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/privateLinkResources", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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 PrivateLinkResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`private_link_resources` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_by_redis_cache( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> Iterable["_models.PrivateLinkResource"]: - """Gets the private link resources that need to be created for a redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.PrivateLinkResource] - :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", self._config.api_version)) - cls: ClsType[_models.PrivateLinkResourceListResult] = 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_list_by_redis_cache_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return 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 = 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) diff --git a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_redis_operations.py b/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_redis_operations.py deleted file mode 100644 index bdade40b99fa..000000000000 --- a/sdk/redis/azure-mgmt-redis/azure/mgmt/redis/operations/_redis_operations.py +++ /dev/null @@ -1,2220 +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. -# -------------------------------------------------------------------------- -from io import IOBase -import sys -from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload -import urllib.parse - -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 .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_check_name_availability_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-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", "/subscriptions/{subscriptionId}/providers/Microsoft.Cache/CheckNameAvailability") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_list_upgrade_notifications_request( - resource_group_name: str, name: str, subscription_id: str, *, history: float, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/listUpgradeNotifications", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _params["history"] = _SERIALIZER.query("history", history, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_request(resource_group_name: str, name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_update_request(resource_group_name: str, name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_delete_request(resource_group_name: str, name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request(resource_group_name: str, name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_list_by_resource_group_request(resource_group_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_list_by_subscription_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: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Cache/redis") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_list_keys_request(resource_group_name: str, name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/listKeys", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_regenerate_key_request( - resource_group_name: str, name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/regenerateKey", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_force_reboot_request(resource_group_name: str, name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/forceReboot", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_import_data_request(resource_group_name: str, name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/import", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_export_data_request(resource_group_name: str, name: str, 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", "2024-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", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{name}/export", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "name": _SERIALIZER.url("name", name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _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_flush_cache_request( - resource_group_name: str, cache_name: str, 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", "2024-11-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/flush", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "cacheName": _SERIALIZER.url( - "cache_name", cache_name, "str", pattern=r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])$" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class RedisOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.redis.RedisManagementClient`'s - :attr:`redis` 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 check_name_availability( - self, - parameters: _models.CheckNameAvailabilityParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Checks that the redis cache name is valid and is not already in use. - - :param parameters: Parameters supplied to the CheckNameAvailability Redis operation. The only - supported resource type is 'Microsoft.Cache/redis'. Required. - :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def check_name_availability( - self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Checks that the redis cache name is valid and is not already in use. - - :param parameters: Parameters supplied to the CheckNameAvailability Redis operation. The only - supported resource type is 'Microsoft.Cache/redis'. 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: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def check_name_availability( # pylint: disable=inconsistent-return-statements - self, parameters: Union[_models.CheckNameAvailabilityParameters, IO[bytes]], **kwargs: Any - ) -> None: - """Checks that the redis cache name is valid and is not already in use. - - :param parameters: Parameters supplied to the CheckNameAvailability Redis operation. The only - supported resource type is 'Microsoft.Cache/redis'. Is either a CheckNameAvailabilityParameters - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.CheckNameAvailabilityParameters or IO[bytes] - :return: None or the result of cls(response) - :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 = 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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "CheckNameAvailabilityParameters") - - _request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def list_upgrade_notifications( - self, resource_group_name: str, name: str, history: float, **kwargs: Any - ) -> Iterable["_models.UpgradeNotification"]: - """Gets any upgrade notifications for a Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param history: how many minutes in past to look for upgrade notifications. Required. - :type history: float - :return: An iterator like instance of either UpgradeNotification or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.UpgradeNotification] - :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", self._config.api_version)) - cls: ClsType[_models.NotificationListResponse] = 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_list_upgrade_notifications_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - history=history, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("NotificationListResponse", 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) - - _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 = 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) - - def _create_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisCreateParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisCreateParameters") - - _request = build_create_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_create( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisCreateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisResource]: - """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Create Redis operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters - :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 either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_create( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisResource]: - """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Create Redis operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_create( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisCreateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.RedisResource]: - """Create or replace (overwrite/recreate, with potential downtime) an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Create Redis operation. Is either a - RedisCreateParameters type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisCreateParameters or IO[bytes] - :return: An instance of LROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisResource] = 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_initial( - resource_group_name=resource_group_name, - name=name, - 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): - deserialized = self._deserialize("RedisResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.RedisResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _update_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisUpdateParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisUpdateParameters") - - _request = build_update_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_update( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisResource]: - """Update an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Update Redis operation. Required. - :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters - :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 either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_update( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.RedisResource]: - """Update an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Update Redis operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_update( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisUpdateParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[_models.RedisResource]: - """Update an existing Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters supplied to the Update Redis operation. Is either a - RedisUpdateParameters type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisUpdateParameters or IO[bytes] - :return: An instance of LROPoller that returns either RedisResource or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisResource] = 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( - resource_group_name=resource_group_name, - name=name, - 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): - deserialized = self._deserialize("RedisResource", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - 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[_models.RedisResource].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.RedisResource]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _delete_initial(self, resource_group_name: str, name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_delete_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_delete(self, resource_group_name: str, name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes a Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :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", self._config.api_version)) - cls: ClsType[None] = 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._delete_initial( - resource_group_name=resource_group_name, - name=name, - api_version=api_version, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - @distributed_trace - def get(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisResource: - """Gets a Redis cache (resource description). - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :return: RedisResource or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisResource - :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", self._config.api_version)) - cls: ClsType[_models.RedisResource] = kwargs.pop("cls", None) - - _request = build_get_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisResource", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.RedisResource"]: - """Lists all Redis caches in a resource group. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :return: An iterator like instance of either RedisResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - cls: ClsType[_models.RedisListResult] = 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_list_by_resource_group_request( - resource_group_name=resource_group_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RedisListResult", 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) - - _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 = 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) - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.RedisResource"]: - """Gets all Redis caches in the specified subscription. - - :return: An iterator like instance of either RedisResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.redis.models.RedisResource] - :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", self._config.api_version)) - cls: ClsType[_models.RedisListResult] = 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_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - _request.url = self._client.format_url(_request.url) - _request.method = "GET" - return _request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RedisListResult", 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) - - _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 = 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) - - @distributed_trace - def list_keys(self, resource_group_name: str, name: str, **kwargs: Any) -> _models.RedisAccessKeys: - """Retrieve a Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :return: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :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", self._config.api_version)) - cls: ClsType[_models.RedisAccessKeys] = kwargs.pop("cls", None) - - _request = build_list_keys_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisAccessKeys", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def regenerate_key( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisRegenerateKeyParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisAccessKeys: - """Regenerate Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which key to regenerate. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def regenerate_key( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisAccessKeys: - """Regenerate Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which key to regenerate. 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: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def regenerate_key( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisRegenerateKeyParameters, IO[bytes]], - **kwargs: Any - ) -> _models.RedisAccessKeys: - """Regenerate Redis cache's access keys. This operation requires write permission to the cache - resource. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which key to regenerate. Is either a RedisRegenerateKeyParameters - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRegenerateKeyParameters or IO[bytes] - :return: RedisAccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisAccessKeys - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisAccessKeys] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisRegenerateKeyParameters") - - _request = build_regenerate_key_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisAccessKeys", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def force_reboot( - self, - resource_group_name: str, - name: str, - parameters: _models.RedisRebootParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisForceRebootResponse: - """Reboot specified Redis node(s). This operation requires write permission to the cache resource. - There can be potential data loss. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which Redis node(s) to reboot. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RedisForceRebootResponse or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def force_reboot( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RedisForceRebootResponse: - """Reboot specified Redis node(s). This operation requires write permission to the cache resource. - There can be potential data loss. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which Redis node(s) to reboot. 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: RedisForceRebootResponse or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def force_reboot( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.RedisRebootParameters, IO[bytes]], - **kwargs: Any - ) -> _models.RedisForceRebootResponse: - """Reboot specified Redis node(s). This operation requires write permission to the cache resource. - There can be potential data loss. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Specifies which Redis node(s) to reboot. Is either a RedisRebootParameters - type or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.RedisRebootParameters or IO[bytes] - :return: RedisForceRebootResponse or the result of cls(response) - :rtype: ~azure.mgmt.redis.models.RedisForceRebootResponse - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedisForceRebootResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RedisRebootParameters") - - _request = build_force_reboot_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("RedisForceRebootResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _import_data_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ImportRDBParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ImportRDBParameters") - - _request = build_import_data_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_import_data( - self, - resource_group_name: str, - name: str, - parameters: _models.ImportRDBParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Import data into Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis import operation. Required. - :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters - :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 either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_import_data( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Import data into Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis import operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_import_data( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ImportRDBParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[None]: - """Import data into Redis cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis import operation. Is either a ImportRDBParameters type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.ImportRDBParameters or IO[bytes] - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = 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._import_data_initial( - resource_group_name=resource_group_name, - name=name, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _export_data_initial( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ExportRDBParameters, 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", self._config.api_version)) - 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" - _json = None - _content = None - if isinstance(parameters, (IOBase, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "ExportRDBParameters") - - _request = build_export_data_request( - resource_group_name=resource_group_name, - name=name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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, 204]: - 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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_export_data( - self, - resource_group_name: str, - name: str, - parameters: _models.ExportRDBParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Export data from the redis cache to blobs in a container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis export operation. Required. - :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters - :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 either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_export_data( - self, - resource_group_name: str, - name: str, - parameters: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[None]: - """Export data from the redis cache to blobs in a container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis export operation. Required. - :type parameters: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_export_data( - self, - resource_group_name: str, - name: str, - parameters: Union[_models.ExportRDBParameters, IO[bytes]], - **kwargs: Any - ) -> LROPoller[None]: - """Export data from the redis cache to blobs in a container. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param name: The name of the Redis cache. Required. - :type name: str - :param parameters: Parameters for Redis export operation. Is either a ExportRDBParameters type - or a IO[bytes] type. Required. - :type parameters: ~azure.mgmt.redis.models.ExportRDBParameters or IO[bytes] - :return: An instance of LROPoller that returns either None or the result of cls(response) - :rtype: ~azure.core.polling.LROPoller[None] - :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", self._config.api_version)) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = 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._export_data_initial( - resource_group_name=resource_group_name, - name=name, - 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): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - 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[None].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - def _flush_cache_initial(self, resource_group_name: str, cache_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_flush_cache_request( - resource_group_name=resource_group_name, - cache_name=cache_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _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 = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def begin_flush_cache( - self, resource_group_name: str, cache_name: str, **kwargs: Any - ) -> LROPoller[_models.OperationStatusResult]: - """Deletes all of the keys in a cache. - - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :param cache_name: The name of the Redis cache. Required. - :type cache_name: str - :return: An instance of LROPoller that returns either OperationStatusResult or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.redis.models.OperationStatusResult] - :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", self._config.api_version)) - cls: ClsType[_models.OperationStatusResult] = 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._flush_cache_initial( - resource_group_name=resource_group_name, - cache_name=cache_name, - api_version=api_version, - 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["Azure-AsyncOperation"] = self._deserialize( - "str", response.headers.get("Azure-AsyncOperation") - ) - - deserialized = self._deserialize("OperationStatusResult", pipeline_response.http_response) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - 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[_models.OperationStatusResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.OperationStatusResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) diff --git a/sdk/redis/azure-mgmt-redis/dev_requirements.txt b/sdk/redis/azure-mgmt-redis/dev_requirements.txt index dafc8467ecc2..36e89061d7a0 100644 --- a/sdk/redis/azure-mgmt-redis/dev_requirements.txt +++ b/sdk/redis/azure-mgmt-redis/dev_requirements.txt @@ -1,3 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../resources/azure-mgmt-resource -aiohttp \ No newline at end of file +aiohttp +azure-identity \ No newline at end of file diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_create_update.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_create_update.py index 163aef7b963a..9a7862407543 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_create_update.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_create_update.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.access_policy_assignment.begin_create_update( @@ -45,6 +45,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyAssignmentCreateUpdate.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyAssignmentCreateUpdate.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_delete.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_delete.py index 491edc10b1a0..60608d899d18 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_delete.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_delete.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.access_policy_assignment.begin_delete( @@ -37,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyAssignmentDelete.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyAssignmentDelete.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_get.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_get.py index 0b3244ea513d..846172a2c869 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_get.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_get.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.access_policy_assignment.get( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyAssignmentGet.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyAssignmentGet.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_list.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_list.py index 8d8dc173b96f..6e5ec4b94809 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_list.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_assignment_list.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.access_policy_assignment.list( @@ -38,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyAssignmentList.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyAssignmentList.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_create_update.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_create_update.py index 2f03da9e34fd..40fba021c168 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_create_update.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_create_update.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.access_policy.begin_create_update( @@ -39,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyCreateUpdate.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyCreateUpdate.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_delete.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_delete.py index d14e747a6e02..a1b0ba7a75e5 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_delete.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_delete.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.access_policy.begin_delete( @@ -37,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyDelete.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyDelete.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_get.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_get.py index 62a1d2a3e6b0..a63b1e037453 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_get.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_get.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.access_policy.get( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyGet.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyGet.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_list.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_list.py index bf7464cdba7a..a96a9a85ae1b 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_list.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_access_policy_list.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.access_policy.list( @@ -38,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAccessPolicyList.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAccessPolicyList.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_async_operation_status.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_async_operation_status.py index 75b7f4df16a0..0ee9135a13a9 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_async_operation_status.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_async_operation_status.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.async_operation_status.get( @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheAsyncOperationStatus.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheAsyncOperationStatus.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_check_name_availability.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_check_name_availability.py index 2c4ba0f0b857..bd8ecfb00001 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_check_name_availability.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_check_name_availability.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.redis.check_name_availability( @@ -35,6 +35,6 @@ def main(): ) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheCheckNameAvailability.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheCheckNameAvailability.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create.py index ec29f4f18716..57b3fff13d81 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create.py @@ -1,8 +1,9 @@ +# 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. # -------------------------------------------------------------------------- @@ -27,7 +28,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_create( @@ -44,7 +45,7 @@ def main(): "shardCount": 2, "sku": {"capacity": 1, "family": "P", "name": "Premium"}, "staticIP": "192.168.0.5", - "subnetId": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", }, "zones": ["1"], }, @@ -52,6 +53,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheCreate.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheCreate.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_automatic_zonal_allocation_policy.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_automatic_zonal_allocation_policy.py index 1de2aff2dced..81f4f43e01f8 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_automatic_zonal_allocation_policy.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_automatic_zonal_allocation_policy.py @@ -1,8 +1,9 @@ +# 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. # -------------------------------------------------------------------------- @@ -27,7 +28,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_create( @@ -43,7 +44,7 @@ def main(): "shardCount": 2, "sku": {"capacity": 1, "family": "P", "name": "Premium"}, "staticIP": "192.168.0.5", - "subnetId": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", "zonalAllocationPolicy": "Automatic", }, }, @@ -51,6 +52,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheCreateAutomaticZonalAllocationPolicy.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheCreateAutomaticZonalAllocationPolicy.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_default_version.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_default_version.py index 72b80752bd1f..1dde34dca3a6 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_default_version.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_default_version.py @@ -1,8 +1,9 @@ +# 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. # -------------------------------------------------------------------------- @@ -27,7 +28,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_create( @@ -43,7 +44,7 @@ def main(): "shardCount": 2, "sku": {"capacity": 1, "family": "P", "name": "Premium"}, "staticIP": "192.168.0.5", - "subnetId": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", }, "zones": ["1"], }, @@ -51,6 +52,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheCreateDefaultVersion.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheCreateDefaultVersion.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_latest_version.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_latest_version.py index 4074e4ed61a3..20033ae66402 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_latest_version.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_latest_version.py @@ -1,8 +1,9 @@ +# 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. # -------------------------------------------------------------------------- @@ -27,7 +28,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_create( @@ -44,7 +45,7 @@ def main(): "shardCount": 2, "sku": {"capacity": 1, "family": "P", "name": "Premium"}, "staticIP": "192.168.0.5", - "subnetId": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", }, "zones": ["1"], }, @@ -52,6 +53,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheCreateLatestVersion.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheCreateLatestVersion.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_no_zones_zonal_allocation_policy.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_no_zones_zonal_allocation_policy.py index 7ddc2ee613cc..2bc119743378 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_no_zones_zonal_allocation_policy.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_no_zones_zonal_allocation_policy.py @@ -1,8 +1,9 @@ +# 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. # -------------------------------------------------------------------------- @@ -27,7 +28,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_create( @@ -43,7 +44,7 @@ def main(): "shardCount": 2, "sku": {"capacity": 1, "family": "P", "name": "Premium"}, "staticIP": "192.168.0.5", - "subnetId": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", "zonalAllocationPolicy": "NoZones", }, }, @@ -51,6 +52,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheCreateNoZonesZonalAllocationPolicy.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheCreateNoZonesZonalAllocationPolicy.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_user_defined_zonal_allocation_policy.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_user_defined_zonal_allocation_policy.py index 7525f8158bd1..d14f0f528a19 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_user_defined_zonal_allocation_policy.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_create_user_defined_zonal_allocation_policy.py @@ -1,8 +1,9 @@ +# 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. # -------------------------------------------------------------------------- @@ -27,7 +28,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_create( @@ -44,7 +45,7 @@ def main(): "shardCount": 2, "sku": {"capacity": 1, "family": "P", "name": "Premium"}, "staticIP": "192.168.0.5", - "subnetId": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", + "subnetId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg2/providers/Microsoft.Network/virtualNetworks/network1/subnets/subnet1", "zonalAllocationPolicy": "UserDefined", }, "zones": ["1"], @@ -53,6 +54,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheCreateUserDefinedZonalAllocationPolicy.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheCreateUserDefinedZonalAllocationPolicy.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete.py index 576e653c58e6..3cb9e73dcf11 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.redis.begin_delete( @@ -36,6 +36,6 @@ def main(): ).result() -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheDelete.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheDelete.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete_private_endpoint_connection.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete_private_endpoint_connection.py index 6cc0e6dc98d9..1eea33582133 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete_private_endpoint_connection.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_delete_private_endpoint_connection.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="{subscriptionId}", + subscription_id="SUBSCRIPTION_ID", ) client.private_endpoint_connections.delete( @@ -37,6 +37,6 @@ def main(): ) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheDeletePrivateEndpointConnection.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheDeletePrivateEndpointConnection.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_export.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_export.py index 13cbd18133f2..90f12b41c253 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_export.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_export.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.redis.begin_export_data( @@ -42,6 +42,6 @@ def main(): ).result() -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheExport.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheExport.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_create.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_create.py index 3bbe55d66819..69b87491b9bb 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_create.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_create.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.firewall_rules.create_or_update( @@ -39,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheFirewallRuleCreate.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheFirewallRuleCreate.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_delete.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_delete.py index 242395d69b59..3dd0c1016087 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_delete.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_delete.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.firewall_rules.delete( @@ -37,6 +37,6 @@ def main(): ) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheFirewallRuleDelete.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheFirewallRuleDelete.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_get.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_get.py index e84f85f9c2ab..c2c4d22f5ca8 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_get.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rule_get.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.firewall_rules.get( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheFirewallRuleGet.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheFirewallRuleGet.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rules_list.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rules_list.py index 32d85f657a89..682808cf0689 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rules_list.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_firewall_rules_list.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.firewall_rules.list( @@ -38,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheFirewallRulesList.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheFirewallRulesList.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_flush.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_flush.py index 1f0e8ee414f3..ad8ddd568809 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_flush.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_flush.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subcription-id", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_flush_cache( @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheFlush.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheFlush.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_force_reboot.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_force_reboot.py index b9c04a12b484..64b1e2a13eec 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_force_reboot.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_force_reboot.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.force_reboot( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheForceReboot.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheForceReboot.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get.py index 373f3f9dd103..61b6aa44a2e3 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.get( @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheGet.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheGet.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get_private_endpoint_connection.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get_private_endpoint_connection.py index c783efb5a18a..6994e07297c7 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get_private_endpoint_connection.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_get_private_endpoint_connection.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="{subscriptionId}", + subscription_id="SUBSCRIPTION_ID", ) response = client.private_endpoint_connections.get( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheGetPrivateEndpointConnection.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheGetPrivateEndpointConnection.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_import.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_import.py index ec9e533722b2..caf96af98f00 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_import.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_import.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.redis.begin_import_data( @@ -41,6 +41,6 @@ def main(): ).result() -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheImport.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheImport.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_create.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_create.py index cdc45766023b..ec08772c84f5 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_create.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_create.py @@ -1,8 +1,9 @@ +# 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. # -------------------------------------------------------------------------- @@ -27,7 +28,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.linked_server.begin_create( @@ -36,7 +37,7 @@ def main(): linked_server_name="cache2", parameters={ "properties": { - "linkedRedisCacheId": "/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Cache/Redis/cache2", + "linkedRedisCacheId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.Cache/Redis/cache2", "linkedRedisCacheLocation": "West US", "serverRole": "Secondary", } @@ -45,6 +46,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheLinkedServer_Create.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheLinkedServer_Create.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_delete.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_delete.py index 21e5e4b27090..dd759c510ed9 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_delete.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_delete.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.linked_server.begin_delete( @@ -37,6 +37,6 @@ def main(): ).result() -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheLinkedServer_Delete.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheLinkedServer_Delete.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_get.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_get.py index 7b01e275de67..88684ba14d7f 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_get.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_get.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.linked_server.get( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheLinkedServer_Get.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheLinkedServer_Get.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_list.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_list.py index 61c031524bb5..260aa0a9a2c3 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_list.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_linked_server_list.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.linked_server.list( @@ -38,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheLinkedServer_List.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheLinkedServer_List.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list.py index 47ba6ba53680..39fa562ac811 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.list_by_subscription() @@ -35,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheList.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheList.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_by_resource_group.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_by_resource_group.py index e222ad6fe66f..009451e13221 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_by_resource_group.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_by_resource_group.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.list_by_resource_group( @@ -37,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheListByResourceGroup.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheListByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_keys.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_keys.py index 813bf7027360..870668bcac60 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_keys.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_keys.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.list_keys( @@ -37,6 +37,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheListKeys.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheListKeys.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_endpoint_connections.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_endpoint_connections.py index 9e936f3be251..76d1d7afd7cb 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_endpoint_connections.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_endpoint_connections.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="{subscriptionId}", + subscription_id="SUBSCRIPTION_ID", ) response = client.private_endpoint_connections.list( @@ -38,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheListPrivateEndpointConnections.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheListPrivateEndpointConnections.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_link_resources.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_link_resources.py index acce4f021a0b..be3baf7196ed 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_link_resources.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_private_link_resources.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="{subscription-id}", + subscription_id="SUBSCRIPTION_ID", ) response = client.private_link_resources.list_by_redis_cache( @@ -38,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheListPrivateLinkResources.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheListPrivateLinkResources.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_upgrade_notifications.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_upgrade_notifications.py index 14e8c93d837e..5cf8caa9c542 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_upgrade_notifications.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_list_upgrade_notifications.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.list_upgrade_notifications( @@ -39,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheListUpgradeNotifications.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheListUpgradeNotifications.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_operations.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_operations.py index b80288dc2bed..3f7c3fe894fd 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_operations.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. # -------------------------------------------------------------------------- @@ -35,6 +35,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheOperations.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheOperations.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_create_or_update.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_create_or_update.py index 6bb35edd15d7..5349edf70d4c 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_create_or_update.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_create_or_update.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.patch_schedules.create_or_update( @@ -46,6 +46,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCachePatchSchedulesCreateOrUpdate.json +# x-ms-original-file: 2025-08-01-preview/RedisCachePatchSchedulesCreateOrUpdate.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_delete.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_delete.py index 648444cddaa8..fb576d0aba5d 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_delete.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_delete.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) client.patch_schedules.delete( @@ -37,6 +37,6 @@ def main(): ) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCachePatchSchedulesDelete.json +# x-ms-original-file: 2025-08-01-preview/RedisCachePatchSchedulesDelete.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_get.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_get.py index f929dc8aa5ff..73a7d62149aa 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_get.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_get.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.patch_schedules.get( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCachePatchSchedulesGet.json +# x-ms-original-file: 2025-08-01-preview/RedisCachePatchSchedulesGet.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_list.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_list.py index 6e2dd23e532f..7ab99a3880f3 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_list.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_patch_schedules_list.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.patch_schedules.list_by_redis_resource( @@ -38,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCachePatchSchedulesList.json +# x-ms-original-file: 2025-08-01-preview/RedisCachePatchSchedulesList.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_put_private_endpoint_connection.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_put_private_endpoint_connection.py index 8c149ffc38fa..c201b9277139 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_put_private_endpoint_connection.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_put_private_endpoint_connection.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="{subscriptionId}", + subscription_id="SUBSCRIPTION_ID", ) response = client.private_endpoint_connections.begin_put( @@ -41,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCachePutPrivateEndpointConnection.json +# x-ms-original-file: 2025-08-01-preview/RedisCachePutPrivateEndpointConnection.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_regenerate_key.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_regenerate_key.py index 7e436d040bdd..5107b31124bd 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_regenerate_key.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_regenerate_key.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.regenerate_key( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheRegenerateKey.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheRegenerateKey.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_update.py b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_update.py index e2c5a2248f9f..3b9350450a60 100644 --- a/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_update.py +++ b/sdk/redis/azure-mgmt-redis/generated_samples/redis_cache_update.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. # -------------------------------------------------------------------------- @@ -27,7 +27,7 @@ def main(): client = RedisManagementClient( credential=DefaultAzureCredential(), - subscription_id="subid", + subscription_id="SUBSCRIPTION_ID", ) response = client.redis.begin_update( @@ -38,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/redis/resource-manager/Microsoft.Cache/stable/2024-11-01/examples/RedisCacheUpdate.json +# x-ms-original-file: 2025-08-01-preview/RedisCacheUpdate.json if __name__ == "__main__": main() diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/conftest.py b/sdk/redis/azure-mgmt-redis/generated_tests/conftest.py index 06d0ae55c85d..ebb218edc4f0 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/conftest.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/conftest.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. # -------------------------------------------------------------------------- import os diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations.py index e8fa58aee424..6e90dd50cf35 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations.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. # -------------------------------------------------------------------------- import pytest @@ -18,6 +18,18 @@ class TestRedisManagementAccessPolicyAssignmentOperations(AzureMgmtRecordedTestC def setup_method(self, method): self.client = self.create_mgmt_client(RedisManagementClient) + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_access_policy_assignment_get(self, resource_group): + response = self.client.access_policy_assignment.get( + resource_group_name=resource_group.name, + cache_name="str", + access_policy_assignment_name="str", + ) + + # please add some check logic here by yourself + # ... + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy def test_access_policy_assignment_begin_create_update(self, resource_group): @@ -26,15 +38,24 @@ def test_access_policy_assignment_begin_create_update(self, resource_group): cache_name="str", access_policy_assignment_name="str", parameters={ - "accessPolicyName": "str", "id": "str", "name": "str", - "objectId": "str", - "objectIdAlias": "str", - "provisioningState": "str", + "properties": { + "accessPolicyName": "str", + "objectId": "str", + "objectIdAlias": "str", + "provisioningState": "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="2024-11-01", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -47,32 +68,17 @@ def test_access_policy_assignment_begin_delete(self, resource_group): resource_group_name=resource_group.name, cache_name="str", access_policy_assignment_name="str", - api_version="2024-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_access_policy_assignment_get(self, resource_group): - response = self.client.access_policy_assignment.get( - resource_group_name=resource_group.name, - cache_name="str", - access_policy_assignment_name="str", - api_version="2024-11-01", - ) - - # please add some check logic here by yourself - # ... - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy def test_access_policy_assignment_list(self, resource_group): response = self.client.access_policy_assignment.list( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", ) result = [r for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations_async.py index 3a4b504bd60e..4d8eac48086e 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_assignment_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -19,6 +19,18 @@ class TestRedisManagementAccessPolicyAssignmentOperationsAsync(AzureMgmtRecorded def setup_method(self, method): self.client = self.create_mgmt_client(RedisManagementClient, is_async=True) + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_access_policy_assignment_get(self, resource_group): + response = await self.client.access_policy_assignment.get( + resource_group_name=resource_group.name, + cache_name="str", + access_policy_assignment_name="str", + ) + + # please add some check logic here by yourself + # ... + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async async def test_access_policy_assignment_begin_create_update(self, resource_group): @@ -28,15 +40,24 @@ async def test_access_policy_assignment_begin_create_update(self, resource_group cache_name="str", access_policy_assignment_name="str", parameters={ - "accessPolicyName": "str", "id": "str", "name": "str", - "objectId": "str", - "objectIdAlias": "str", - "provisioningState": "str", + "properties": { + "accessPolicyName": "str", + "objectId": "str", + "objectIdAlias": "str", + "provisioningState": "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="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -51,33 +72,18 @@ async def test_access_policy_assignment_begin_delete(self, resource_group): resource_group_name=resource_group.name, cache_name="str", access_policy_assignment_name="str", - api_version="2024-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_access_policy_assignment_get(self, resource_group): - response = await self.client.access_policy_assignment.get( - resource_group_name=resource_group.name, - cache_name="str", - access_policy_assignment_name="str", - api_version="2024-11-01", - ) - - # please add some check logic here by yourself - # ... - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async async def test_access_policy_assignment_list(self, resource_group): response = self.client.access_policy_assignment.list( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", ) result = [r async for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations.py index dfbafd6ec998..e094cec42674 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations.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. # -------------------------------------------------------------------------- import pytest @@ -20,26 +20,37 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_access_policy_begin_create_update(self, resource_group): - response = self.client.access_policy.begin_create_update( + def test_access_policy_get(self, resource_group): + response = self.client.access_policy.get( resource_group_name=resource_group.name, cache_name="str", access_policy_name="str", - parameters={"id": "str", "name": "str", "permissions": "str", "provisioningState": "str", "type": "str"}, - api_version="2024-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_access_policy_begin_delete(self, resource_group): - response = self.client.access_policy.begin_delete( + def test_access_policy_begin_create_update(self, resource_group): + response = self.client.access_policy.begin_create_update( resource_group_name=resource_group.name, cache_name="str", access_policy_name="str", - api_version="2024-11-01", + parameters={ + "id": "str", + "name": "str", + "properties": {"permissions": "str", "provisioningState": "str", "type": "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", + }, ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -47,13 +58,12 @@ def test_access_policy_begin_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_access_policy_get(self, resource_group): - response = self.client.access_policy.get( + def test_access_policy_begin_delete(self, resource_group): + response = self.client.access_policy.begin_delete( resource_group_name=resource_group.name, cache_name="str", access_policy_name="str", - api_version="2024-11-01", - ) + ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself # ... @@ -64,7 +74,6 @@ def test_access_policy_list(self, resource_group): response = self.client.access_policy.list( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", ) result = [r for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations_async.py index edef4c030ae7..e86607fba433 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_access_policy_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -19,6 +19,18 @@ class TestRedisManagementAccessPolicyOperationsAsync(AzureMgmtRecordedTestCase): def setup_method(self, method): self.client = self.create_mgmt_client(RedisManagementClient, is_async=True) + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_access_policy_get(self, resource_group): + response = await self.client.access_policy.get( + resource_group_name=resource_group.name, + cache_name="str", + access_policy_name="str", + ) + + # please add some check logic here by yourself + # ... + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async async def test_access_policy_begin_create_update(self, resource_group): @@ -30,11 +42,17 @@ async def test_access_policy_begin_create_update(self, resource_group): parameters={ "id": "str", "name": "str", - "permissions": "str", - "provisioningState": "str", + "properties": {"permissions": "str", "provisioningState": "str", "type": "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="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -49,33 +67,18 @@ async def test_access_policy_begin_delete(self, resource_group): resource_group_name=resource_group.name, cache_name="str", access_policy_name="str", - api_version="2024-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_access_policy_get(self, resource_group): - response = await self.client.access_policy.get( - resource_group_name=resource_group.name, - cache_name="str", - access_policy_name="str", - api_version="2024-11-01", - ) - - # please add some check logic here by yourself - # ... - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async async def test_access_policy_list(self, resource_group): response = self.client.access_policy.list( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", ) result = [r async for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations.py index 4f60551242c2..9668f51cb090 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations.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. # -------------------------------------------------------------------------- import pytest @@ -24,7 +24,6 @@ def test_async_operation_status_get(self, resource_group): response = self.client.async_operation_status.get( location="str", operation_id="str", - api_version="2024-11-01", ) # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations_async.py index b72b910e703d..f213662a0bc0 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_async_operation_status_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -25,7 +25,6 @@ async def test_async_operation_status_get(self, resource_group): response = await self.client.async_operation_status.get( location="str", operation_id="str", - api_version="2024-11-01", ) # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations.py index c58722f1d82d..0f01724e5fd5 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations.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. # -------------------------------------------------------------------------- import pytest @@ -20,13 +20,13 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_firewall_rules_list(self, resource_group): - response = self.client.firewall_rules.list( + def test_firewall_rules_get(self, resource_group): + response = self.client.firewall_rules.get( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", + rule_name="str", ) - result = [r for r in response] + # please add some check logic here by yourself # ... @@ -37,8 +37,20 @@ def test_firewall_rules_create_or_update(self, resource_group): resource_group_name=resource_group.name, cache_name="str", rule_name="str", - parameters={"endIP": "str", "startIP": "str", "id": "str", "name": "str", "type": "str"}, - api_version="2024-11-01", + parameters={ + "properties": {"endIP": "str", "startIP": "str"}, + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, ) # please add some check logic here by yourself @@ -46,12 +58,11 @@ def test_firewall_rules_create_or_update(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_firewall_rules_get(self, resource_group): - response = self.client.firewall_rules.get( + def test_firewall_rules_delete(self, resource_group): + response = self.client.firewall_rules.delete( resource_group_name=resource_group.name, cache_name="str", rule_name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -59,13 +70,11 @@ def test_firewall_rules_get(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_firewall_rules_delete(self, resource_group): - response = self.client.firewall_rules.delete( + def test_firewall_rules_list(self, resource_group): + response = self.client.firewall_rules.list( resource_group_name=resource_group.name, cache_name="str", - rule_name="str", - api_version="2024-11-01", ) - + result = [r for r in response] # please add some check logic here by yourself # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations_async.py index 7c9e04cf2535..8af7838dda2c 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_firewall_rules_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -21,13 +21,13 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_firewall_rules_list(self, resource_group): - response = self.client.firewall_rules.list( + async def test_firewall_rules_get(self, resource_group): + response = await self.client.firewall_rules.get( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", + rule_name="str", ) - result = [r async for r in response] + # please add some check logic here by yourself # ... @@ -38,8 +38,20 @@ async def test_firewall_rules_create_or_update(self, resource_group): resource_group_name=resource_group.name, cache_name="str", rule_name="str", - parameters={"endIP": "str", "startIP": "str", "id": "str", "name": "str", "type": "str"}, - api_version="2024-11-01", + parameters={ + "properties": {"endIP": "str", "startIP": "str"}, + "id": "str", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, ) # please add some check logic here by yourself @@ -47,12 +59,11 @@ async def test_firewall_rules_create_or_update(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_firewall_rules_get(self, resource_group): - response = await self.client.firewall_rules.get( + async def test_firewall_rules_delete(self, resource_group): + response = await self.client.firewall_rules.delete( resource_group_name=resource_group.name, cache_name="str", rule_name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -60,13 +71,11 @@ async def test_firewall_rules_get(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_firewall_rules_delete(self, resource_group): - response = await self.client.firewall_rules.delete( + async def test_firewall_rules_list(self, resource_group): + response = self.client.firewall_rules.list( resource_group_name=resource_group.name, cache_name="str", - rule_name="str", - api_version="2024-11-01", ) - + result = [r async for r in response] # please add some check logic here by yourself # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations.py index 8afb94972fdb..9effdcc3bc7b 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations.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. # -------------------------------------------------------------------------- import pytest @@ -20,32 +20,32 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_linked_server_begin_create(self, resource_group): - response = self.client.linked_server.begin_create( + def test_linked_server_get(self, resource_group): + response = self.client.linked_server.get( resource_group_name=resource_group.name, name="str", linked_server_name="str", - parameters={ - "linkedRedisCacheId": "str", - "linkedRedisCacheLocation": "str", - "serverRole": "str", - "geoReplicatedPrimaryHostName": "str", - "primaryHostName": "str", - }, - api_version="2024-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_linked_server_begin_delete(self, resource_group): - response = self.client.linked_server.begin_delete( + def test_linked_server_begin_create(self, resource_group): + response = self.client.linked_server.begin_create( resource_group_name=resource_group.name, name="str", linked_server_name="str", - api_version="2024-11-01", + parameters={ + "properties": { + "linkedRedisCacheId": "str", + "linkedRedisCacheLocation": "str", + "serverRole": "str", + "geoReplicatedPrimaryHostName": "str", + "primaryHostName": "str", + } + }, ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -53,13 +53,12 @@ def test_linked_server_begin_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_linked_server_get(self, resource_group): - response = self.client.linked_server.get( + def test_linked_server_begin_delete(self, resource_group): + response = self.client.linked_server.begin_delete( resource_group_name=resource_group.name, name="str", linked_server_name="str", - api_version="2024-11-01", - ) + ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself # ... @@ -70,7 +69,6 @@ def test_linked_server_list(self, resource_group): response = self.client.linked_server.list( resource_group_name=resource_group.name, name="str", - api_version="2024-11-01", ) result = [r for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations_async.py index 65e53a41af8c..f666623591da 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_linked_server_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -19,6 +19,18 @@ class TestRedisManagementLinkedServerOperationsAsync(AzureMgmtRecordedTestCase): def setup_method(self, method): self.client = self.create_mgmt_client(RedisManagementClient, is_async=True) + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_linked_server_get(self, resource_group): + response = await self.client.linked_server.get( + resource_group_name=resource_group.name, + name="str", + linked_server_name="str", + ) + + # please add some check logic here by yourself + # ... + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async async def test_linked_server_begin_create(self, resource_group): @@ -28,13 +40,14 @@ async def test_linked_server_begin_create(self, resource_group): name="str", linked_server_name="str", parameters={ - "linkedRedisCacheId": "str", - "linkedRedisCacheLocation": "str", - "serverRole": "str", - "geoReplicatedPrimaryHostName": "str", - "primaryHostName": "str", + "properties": { + "linkedRedisCacheId": "str", + "linkedRedisCacheLocation": "str", + "serverRole": "str", + "geoReplicatedPrimaryHostName": "str", + "primaryHostName": "str", + } }, - api_version="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -49,33 +62,18 @@ async def test_linked_server_begin_delete(self, resource_group): resource_group_name=resource_group.name, name="str", linked_server_name="str", - api_version="2024-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_linked_server_get(self, resource_group): - response = await self.client.linked_server.get( - resource_group_name=resource_group.name, - name="str", - linked_server_name="str", - api_version="2024-11-01", - ) - - # please add some check logic here by yourself - # ... - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async async def test_linked_server_list(self, resource_group): response = self.client.linked_server.list( resource_group_name=resource_group.name, name="str", - api_version="2024-11-01", ) result = [r async for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations.py index 94cd8ed4f19e..ccf79f1ad04c 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations.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. # -------------------------------------------------------------------------- import pytest @@ -21,9 +21,7 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy def test_operations_list(self, resource_group): - response = self.client.operations.list( - api_version="2024-11-01", - ) + response = self.client.operations.list() result = [r for r in response] # please add some check logic here by yourself # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations_async.py index 86d0ed4ad979..c8f029993320 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -22,9 +22,7 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async async def test_operations_list(self, resource_group): - response = self.client.operations.list( - api_version="2024-11-01", - ) + response = self.client.operations.list() result = [r async for r in response] # please add some check logic here by yourself # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations.py index c3b54031a1fa..7c6e05abf832 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations.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. # -------------------------------------------------------------------------- import pytest @@ -20,13 +20,13 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_patch_schedules_list_by_redis_resource(self, resource_group): - response = self.client.patch_schedules.list_by_redis_resource( + def test_patch_schedules_get(self, resource_group): + response = self.client.patch_schedules.get( resource_group_name=resource_group.name, - cache_name="str", - api_version="2024-11-01", + name="str", + default="str", ) - result = [r for r in response] + # please add some check logic here by yourself # ... @@ -38,13 +38,22 @@ def test_patch_schedules_create_or_update(self, resource_group): name="str", default="str", parameters={ - "scheduleEntries": [{"dayOfWeek": "str", "startHourUtc": 0, "maintenanceWindow": "1 day, 0:00:00"}], + "properties": { + "scheduleEntries": [{"dayOfWeek": "str", "startHourUtc": 0, "maintenanceWindow": "1 day, 0:00:00"}] + }, "id": "str", "location": "str", "name": "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="2024-11-01", ) # please add some check logic here by yourself @@ -57,7 +66,6 @@ def test_patch_schedules_delete(self, resource_group): resource_group_name=resource_group.name, name="str", default="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -65,13 +73,11 @@ def test_patch_schedules_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_patch_schedules_get(self, resource_group): - response = self.client.patch_schedules.get( + def test_patch_schedules_list_by_redis_resource(self, resource_group): + response = self.client.patch_schedules.list_by_redis_resource( resource_group_name=resource_group.name, - name="str", - default="str", - api_version="2024-11-01", + cache_name="str", ) - + result = [r for r in response] # please add some check logic here by yourself # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations_async.py index 9f5b98e247b3..0ed8a189451a 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_patch_schedules_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -21,13 +21,13 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_patch_schedules_list_by_redis_resource(self, resource_group): - response = self.client.patch_schedules.list_by_redis_resource( + async def test_patch_schedules_get(self, resource_group): + response = await self.client.patch_schedules.get( resource_group_name=resource_group.name, - cache_name="str", - api_version="2024-11-01", + name="str", + default="str", ) - result = [r async for r in response] + # please add some check logic here by yourself # ... @@ -39,13 +39,22 @@ async def test_patch_schedules_create_or_update(self, resource_group): name="str", default="str", parameters={ - "scheduleEntries": [{"dayOfWeek": "str", "startHourUtc": 0, "maintenanceWindow": "1 day, 0:00:00"}], + "properties": { + "scheduleEntries": [{"dayOfWeek": "str", "startHourUtc": 0, "maintenanceWindow": "1 day, 0:00:00"}] + }, "id": "str", "location": "str", "name": "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="2024-11-01", ) # please add some check logic here by yourself @@ -58,7 +67,6 @@ async def test_patch_schedules_delete(self, resource_group): resource_group_name=resource_group.name, name="str", default="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -66,13 +74,11 @@ async def test_patch_schedules_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_patch_schedules_get(self, resource_group): - response = await self.client.patch_schedules.get( + async def test_patch_schedules_list_by_redis_resource(self, resource_group): + response = self.client.patch_schedules.list_by_redis_resource( resource_group_name=resource_group.name, - name="str", - default="str", - api_version="2024-11-01", + cache_name="str", ) - + result = [r async for r in response] # please add some check logic here by yourself # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations.py index 27f3cb3e8374..602a96100c91 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations.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. # -------------------------------------------------------------------------- import pytest @@ -18,18 +18,6 @@ class TestRedisManagementPrivateEndpointConnectionsOperations(AzureMgmtRecordedT def setup_method(self, method): self.client = self.create_mgmt_client(RedisManagementClient) - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_private_endpoint_connections_list(self, resource_group): - response = self.client.private_endpoint_connections.list( - resource_group_name=resource_group.name, - cache_name="str", - api_version="2024-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_private_endpoint_connections_get(self, resource_group): @@ -37,7 +25,6 @@ def test_private_endpoint_connections_get(self, resource_group): resource_group_name=resource_group.name, cache_name="str", private_endpoint_connection_name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -53,12 +40,26 @@ def test_private_endpoint_connections_begin_put(self, resource_group): properties={ "id": "str", "name": "str", - "privateEndpoint": {"id": "str"}, - "privateLinkServiceConnectionState": {"actionsRequired": "str", "description": "str", "status": "str"}, - "provisioningState": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "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="2024-11-01", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -71,8 +72,18 @@ def test_private_endpoint_connections_delete(self, resource_group): resource_group_name=resource_group.name, cache_name="str", private_endpoint_connection_name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_private_endpoint_connections_list(self, resource_group): + response = self.client.private_endpoint_connections.list( + resource_group_name=resource_group.name, + cache_name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations_async.py index a22d50d73ef4..10d78f844fd3 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_endpoint_connections_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -19,18 +19,6 @@ class TestRedisManagementPrivateEndpointConnectionsOperationsAsync(AzureMgmtReco def setup_method(self, method): self.client = self.create_mgmt_client(RedisManagementClient, is_async=True) - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_private_endpoint_connections_list(self, resource_group): - response = self.client.private_endpoint_connections.list( - resource_group_name=resource_group.name, - cache_name="str", - api_version="2024-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_private_endpoint_connections_get(self, resource_group): @@ -38,7 +26,6 @@ async def test_private_endpoint_connections_get(self, resource_group): resource_group_name=resource_group.name, cache_name="str", private_endpoint_connection_name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -55,16 +42,26 @@ async def test_private_endpoint_connections_begin_put(self, resource_group): properties={ "id": "str", "name": "str", - "privateEndpoint": {"id": "str"}, - "privateLinkServiceConnectionState": { - "actionsRequired": "str", - "description": "str", - "status": "str", + "properties": { + "privateLinkServiceConnectionState": { + "actionsRequired": "str", + "description": "str", + "status": "str", + }, + "groupIds": ["str"], + "privateEndpoint": {"id": "str"}, + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", }, - "provisioningState": "str", "type": "str", }, - api_version="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -78,8 +75,18 @@ async def test_private_endpoint_connections_delete(self, resource_group): resource_group_name=resource_group.name, cache_name="str", private_endpoint_connection_name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_private_endpoint_connections_list(self, resource_group): + response = self.client.private_endpoint_connections.list( + resource_group_name=resource_group.name, + cache_name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations.py index b48430903cdc..96d2e92a7354 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations.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. # -------------------------------------------------------------------------- import pytest @@ -24,7 +24,6 @@ def test_private_link_resources_list_by_redis_cache(self, resource_group): response = self.client.private_link_resources.list_by_redis_cache( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", ) result = [r for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations_async.py index c0b0a875c027..81f42bacb752 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_private_link_resources_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -25,7 +25,6 @@ async def test_private_link_resources_list_by_redis_cache(self, resource_group): response = self.client.private_link_resources.list_by_redis_cache( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-11-01", ) result = [r async for r in response] # please add some check logic here by yourself diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations.py index b9fb448f27ab..baf0786316f5 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations.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. # -------------------------------------------------------------------------- import pytest @@ -20,25 +20,12 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_redis_check_name_availability(self, resource_group): - response = self.client.redis.check_name_availability( - parameters={"name": "str", "type": "str"}, - api_version="2024-11-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy - def test_redis_list_upgrade_notifications(self, resource_group): - response = self.client.redis.list_upgrade_notifications( + def test_redis_get(self, resource_group): + response = self.client.redis.get( resource_group_name=resource_group.name, name="str", - history=0.0, - api_version="2024-11-01", ) - result = [r for r in response] + # please add some check logic here by yourself # ... @@ -50,51 +37,52 @@ def test_redis_begin_create(self, resource_group): name="str", parameters={ "location": "str", - "sku": {"capacity": 0, "family": "str", "name": "str"}, - "disableAccessKeyAuthentication": False, - "enableNonSslPort": False, + "properties": { + "sku": {"capacity": 0, "family": "str", "name": "str"}, + "disableAccessKeyAuthentication": bool, + "enableNonSslPort": bool, + "minimumTlsVersion": "str", + "publicNetworkAccess": "str", + "redisConfiguration": { + "aad-enabled": "str", + "aof-backup-enabled": "str", + "aof-storage-connection-string-0": "str", + "aof-storage-connection-string-1": "str", + "authnotrequired": "str", + "maxclients": "str", + "maxfragmentationmemory-reserved": "str", + "maxmemory-delta": "str", + "maxmemory-policy": "str", + "maxmemory-reserved": "str", + "notify-keyspace-events": "str", + "preferred-data-archive-auth-method": "str", + "preferred-data-persistence-auth-method": "str", + "rdb-backup-enabled": "str", + "rdb-backup-frequency": "str", + "rdb-backup-max-snapshot-count": "str", + "rdb-storage-connection-string": "str", + "storage-subscription-id": "str", + "zonal-configuration": "str", + }, + "redisVersion": "str", + "replicasPerMaster": 0, + "replicasPerPrimary": 0, + "shardCount": 0, + "staticIP": "str", + "subnetId": "str", + "tenantSettings": {"str": "str"}, + "updateChannel": "str", + "zonalAllocationPolicy": "str", + }, "identity": { "type": "str", "principalId": "str", "tenantId": "str", "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, }, - "minimumTlsVersion": "str", - "publicNetworkAccess": "Enabled", - "redisConfiguration": { - "aad-enabled": "str", - "aof-backup-enabled": "str", - "aof-storage-connection-string-0": "str", - "aof-storage-connection-string-1": "str", - "authnotrequired": "str", - "maxclients": "str", - "maxfragmentationmemory-reserved": "str", - "maxmemory-delta": "str", - "maxmemory-policy": "str", - "maxmemory-reserved": "str", - "notify-keyspace-events": "str", - "preferred-data-archive-auth-method": "str", - "preferred-data-persistence-auth-method": "str", - "rdb-backup-enabled": "str", - "rdb-backup-frequency": "str", - "rdb-backup-max-snapshot-count": "str", - "rdb-storage-connection-string": "str", - "storage-subscription-id": "str", - "zonal-configuration": "str", - }, - "redisVersion": "str", - "replicasPerMaster": 0, - "replicasPerPrimary": 0, - "shardCount": 0, - "staticIP": "str", - "subnetId": "str", "tags": {"str": "str"}, - "tenantSettings": {"str": "str"}, - "updateChannel": "str", - "zonalAllocationPolicy": "str", "zones": ["str"], }, - api_version="2024-11-01", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -107,48 +95,49 @@ def test_redis_begin_update(self, resource_group): resource_group_name=resource_group.name, name="str", parameters={ - "disableAccessKeyAuthentication": False, - "enableNonSslPort": False, "identity": { "type": "str", "principalId": "str", "tenantId": "str", "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, }, - "minimumTlsVersion": "str", - "publicNetworkAccess": "Enabled", - "redisConfiguration": { - "aad-enabled": "str", - "aof-backup-enabled": "str", - "aof-storage-connection-string-0": "str", - "aof-storage-connection-string-1": "str", - "authnotrequired": "str", - "maxclients": "str", - "maxfragmentationmemory-reserved": "str", - "maxmemory-delta": "str", - "maxmemory-policy": "str", - "maxmemory-reserved": "str", - "notify-keyspace-events": "str", - "preferred-data-archive-auth-method": "str", - "preferred-data-persistence-auth-method": "str", - "rdb-backup-enabled": "str", - "rdb-backup-frequency": "str", - "rdb-backup-max-snapshot-count": "str", - "rdb-storage-connection-string": "str", - "storage-subscription-id": "str", - "zonal-configuration": "str", + "properties": { + "disableAccessKeyAuthentication": bool, + "enableNonSslPort": bool, + "minimumTlsVersion": "str", + "publicNetworkAccess": "str", + "redisConfiguration": { + "aad-enabled": "str", + "aof-backup-enabled": "str", + "aof-storage-connection-string-0": "str", + "aof-storage-connection-string-1": "str", + "authnotrequired": "str", + "maxclients": "str", + "maxfragmentationmemory-reserved": "str", + "maxmemory-delta": "str", + "maxmemory-policy": "str", + "maxmemory-reserved": "str", + "notify-keyspace-events": "str", + "preferred-data-archive-auth-method": "str", + "preferred-data-persistence-auth-method": "str", + "rdb-backup-enabled": "str", + "rdb-backup-frequency": "str", + "rdb-backup-max-snapshot-count": "str", + "rdb-storage-connection-string": "str", + "storage-subscription-id": "str", + "zonal-configuration": "str", + }, + "redisVersion": "str", + "replicasPerMaster": 0, + "replicasPerPrimary": 0, + "shardCount": 0, + "sku": {"capacity": 0, "family": "str", "name": "str"}, + "tenantSettings": {"str": "str"}, + "updateChannel": "str", + "zonalAllocationPolicy": "str", }, - "redisVersion": "str", - "replicasPerMaster": 0, - "replicasPerPrimary": 0, - "shardCount": 0, - "sku": {"capacity": 0, "family": "str", "name": "str"}, "tags": {"str": "str"}, - "tenantSettings": {"str": "str"}, - "updateChannel": "str", - "zonalAllocationPolicy": "str", }, - api_version="2024-11-01", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -160,7 +149,6 @@ def test_redis_begin_delete(self, resource_group): response = self.client.redis.begin_delete( resource_group_name=resource_group.name, name="str", - api_version="2024-11-01", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -168,32 +156,29 @@ def test_redis_begin_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_redis_get(self, resource_group): - response = self.client.redis.get( + def test_redis_list_by_resource_group(self, resource_group): + response = self.client.redis.list_by_resource_group( resource_group_name=resource_group.name, - name="str", - api_version="2024-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_redis_list_by_resource_group(self, resource_group): - response = self.client.redis.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2024-11-01", - ) + def test_redis_list_by_subscription(self, resource_group): + response = self.client.redis.list_by_subscription() result = [r for r in response] # please add some check logic here by yourself # ... @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy - def test_redis_list_by_subscription(self, resource_group): - response = self.client.redis.list_by_subscription( - api_version="2024-11-01", + def test_redis_list_upgrade_notifications(self, resource_group): + response = self.client.redis.list_upgrade_notifications( + resource_group_name=resource_group.name, + name="str", + history=0.0, ) result = [r for r in response] # please add some check logic here by yourself @@ -205,7 +190,6 @@ def test_redis_list_keys(self, resource_group): response = self.client.redis.list_keys( resource_group_name=resource_group.name, name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -218,7 +202,6 @@ def test_redis_regenerate_key(self, resource_group): resource_group_name=resource_group.name, name="str", parameters={"keyType": "str"}, - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -231,7 +214,6 @@ def test_redis_force_reboot(self, resource_group): resource_group_name=resource_group.name, name="str", parameters={"ports": [0], "rebootType": "str", "shardId": 0}, - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -249,7 +231,6 @@ def test_redis_begin_import_data(self, resource_group): "preferred-data-archive-auth-method": "str", "storage-subscription-id": "str", }, - api_version="2024-11-01", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -268,7 +249,6 @@ def test_redis_begin_export_data(self, resource_group): "preferred-data-archive-auth-method": "str", "storage-subscription-id": "str", }, - api_version="2024-11-01", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -280,8 +260,17 @@ def test_redis_begin_flush_cache(self, resource_group): response = self.client.redis.begin_flush_cache( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-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_redis_check_name_availability(self, resource_group): + response = self.client.redis.check_name_availability( + parameters={"name": "str", "type": "str"}, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations_async.py b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations_async.py index 9329805df94c..cd8034108f01 100644 --- a/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations_async.py +++ b/sdk/redis/azure-mgmt-redis/generated_tests/test_redis_management_redis_operations_async.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. # -------------------------------------------------------------------------- import pytest @@ -21,25 +21,12 @@ def setup_method(self, method): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_redis_check_name_availability(self, resource_group): - response = await self.client.redis.check_name_availability( - parameters={"name": "str", "type": "str"}, - api_version="2024-11-01", - ) - - # please add some check logic here by yourself - # ... - - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - @recorded_by_proxy_async - async def test_redis_list_upgrade_notifications(self, resource_group): - response = self.client.redis.list_upgrade_notifications( + async def test_redis_get(self, resource_group): + response = await self.client.redis.get( resource_group_name=resource_group.name, name="str", - history=0.0, - api_version="2024-11-01", ) - result = [r async for r in response] + # please add some check logic here by yourself # ... @@ -52,51 +39,52 @@ async def test_redis_begin_create(self, resource_group): name="str", parameters={ "location": "str", - "sku": {"capacity": 0, "family": "str", "name": "str"}, - "disableAccessKeyAuthentication": False, - "enableNonSslPort": False, + "properties": { + "sku": {"capacity": 0, "family": "str", "name": "str"}, + "disableAccessKeyAuthentication": bool, + "enableNonSslPort": bool, + "minimumTlsVersion": "str", + "publicNetworkAccess": "str", + "redisConfiguration": { + "aad-enabled": "str", + "aof-backup-enabled": "str", + "aof-storage-connection-string-0": "str", + "aof-storage-connection-string-1": "str", + "authnotrequired": "str", + "maxclients": "str", + "maxfragmentationmemory-reserved": "str", + "maxmemory-delta": "str", + "maxmemory-policy": "str", + "maxmemory-reserved": "str", + "notify-keyspace-events": "str", + "preferred-data-archive-auth-method": "str", + "preferred-data-persistence-auth-method": "str", + "rdb-backup-enabled": "str", + "rdb-backup-frequency": "str", + "rdb-backup-max-snapshot-count": "str", + "rdb-storage-connection-string": "str", + "storage-subscription-id": "str", + "zonal-configuration": "str", + }, + "redisVersion": "str", + "replicasPerMaster": 0, + "replicasPerPrimary": 0, + "shardCount": 0, + "staticIP": "str", + "subnetId": "str", + "tenantSettings": {"str": "str"}, + "updateChannel": "str", + "zonalAllocationPolicy": "str", + }, "identity": { "type": "str", "principalId": "str", "tenantId": "str", "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, }, - "minimumTlsVersion": "str", - "publicNetworkAccess": "Enabled", - "redisConfiguration": { - "aad-enabled": "str", - "aof-backup-enabled": "str", - "aof-storage-connection-string-0": "str", - "aof-storage-connection-string-1": "str", - "authnotrequired": "str", - "maxclients": "str", - "maxfragmentationmemory-reserved": "str", - "maxmemory-delta": "str", - "maxmemory-policy": "str", - "maxmemory-reserved": "str", - "notify-keyspace-events": "str", - "preferred-data-archive-auth-method": "str", - "preferred-data-persistence-auth-method": "str", - "rdb-backup-enabled": "str", - "rdb-backup-frequency": "str", - "rdb-backup-max-snapshot-count": "str", - "rdb-storage-connection-string": "str", - "storage-subscription-id": "str", - "zonal-configuration": "str", - }, - "redisVersion": "str", - "replicasPerMaster": 0, - "replicasPerPrimary": 0, - "shardCount": 0, - "staticIP": "str", - "subnetId": "str", "tags": {"str": "str"}, - "tenantSettings": {"str": "str"}, - "updateChannel": "str", - "zonalAllocationPolicy": "str", "zones": ["str"], }, - api_version="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -111,48 +99,49 @@ async def test_redis_begin_update(self, resource_group): resource_group_name=resource_group.name, name="str", parameters={ - "disableAccessKeyAuthentication": False, - "enableNonSslPort": False, "identity": { "type": "str", "principalId": "str", "tenantId": "str", "userAssignedIdentities": {"str": {"clientId": "str", "principalId": "str"}}, }, - "minimumTlsVersion": "str", - "publicNetworkAccess": "Enabled", - "redisConfiguration": { - "aad-enabled": "str", - "aof-backup-enabled": "str", - "aof-storage-connection-string-0": "str", - "aof-storage-connection-string-1": "str", - "authnotrequired": "str", - "maxclients": "str", - "maxfragmentationmemory-reserved": "str", - "maxmemory-delta": "str", - "maxmemory-policy": "str", - "maxmemory-reserved": "str", - "notify-keyspace-events": "str", - "preferred-data-archive-auth-method": "str", - "preferred-data-persistence-auth-method": "str", - "rdb-backup-enabled": "str", - "rdb-backup-frequency": "str", - "rdb-backup-max-snapshot-count": "str", - "rdb-storage-connection-string": "str", - "storage-subscription-id": "str", - "zonal-configuration": "str", + "properties": { + "disableAccessKeyAuthentication": bool, + "enableNonSslPort": bool, + "minimumTlsVersion": "str", + "publicNetworkAccess": "str", + "redisConfiguration": { + "aad-enabled": "str", + "aof-backup-enabled": "str", + "aof-storage-connection-string-0": "str", + "aof-storage-connection-string-1": "str", + "authnotrequired": "str", + "maxclients": "str", + "maxfragmentationmemory-reserved": "str", + "maxmemory-delta": "str", + "maxmemory-policy": "str", + "maxmemory-reserved": "str", + "notify-keyspace-events": "str", + "preferred-data-archive-auth-method": "str", + "preferred-data-persistence-auth-method": "str", + "rdb-backup-enabled": "str", + "rdb-backup-frequency": "str", + "rdb-backup-max-snapshot-count": "str", + "rdb-storage-connection-string": "str", + "storage-subscription-id": "str", + "zonal-configuration": "str", + }, + "redisVersion": "str", + "replicasPerMaster": 0, + "replicasPerPrimary": 0, + "shardCount": 0, + "sku": {"capacity": 0, "family": "str", "name": "str"}, + "tenantSettings": {"str": "str"}, + "updateChannel": "str", + "zonalAllocationPolicy": "str", }, - "redisVersion": "str", - "replicasPerMaster": 0, - "replicasPerPrimary": 0, - "shardCount": 0, - "sku": {"capacity": 0, "family": "str", "name": "str"}, "tags": {"str": "str"}, - "tenantSettings": {"str": "str"}, - "updateChannel": "str", - "zonalAllocationPolicy": "str", }, - api_version="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -166,7 +155,6 @@ async def test_redis_begin_delete(self, resource_group): await self.client.redis.begin_delete( resource_group_name=resource_group.name, name="str", - api_version="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -175,32 +163,29 @@ async def test_redis_begin_delete(self, resource_group): @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) @recorded_by_proxy_async - async def test_redis_get(self, resource_group): - response = await self.client.redis.get( + async def test_redis_list_by_resource_group(self, resource_group): + response = self.client.redis.list_by_resource_group( resource_group_name=resource_group.name, - name="str", - api_version="2024-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_redis_list_by_resource_group(self, resource_group): - response = self.client.redis.list_by_resource_group( - resource_group_name=resource_group.name, - api_version="2024-11-01", - ) + async def test_redis_list_by_subscription(self, resource_group): + response = self.client.redis.list_by_subscription() 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_redis_list_by_subscription(self, resource_group): - response = self.client.redis.list_by_subscription( - api_version="2024-11-01", + async def test_redis_list_upgrade_notifications(self, resource_group): + response = self.client.redis.list_upgrade_notifications( + resource_group_name=resource_group.name, + name="str", + history=0.0, ) result = [r async for r in response] # please add some check logic here by yourself @@ -212,7 +197,6 @@ async def test_redis_list_keys(self, resource_group): response = await self.client.redis.list_keys( resource_group_name=resource_group.name, name="str", - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -225,7 +209,6 @@ async def test_redis_regenerate_key(self, resource_group): resource_group_name=resource_group.name, name="str", parameters={"keyType": "str"}, - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -238,7 +221,6 @@ async def test_redis_force_reboot(self, resource_group): resource_group_name=resource_group.name, name="str", parameters={"ports": [0], "rebootType": "str", "shardId": 0}, - api_version="2024-11-01", ) # please add some check logic here by yourself @@ -257,7 +239,6 @@ async def test_redis_begin_import_data(self, resource_group): "preferred-data-archive-auth-method": "str", "storage-subscription-id": "str", }, - api_version="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -278,7 +259,6 @@ async def test_redis_begin_export_data(self, resource_group): "preferred-data-archive-auth-method": "str", "storage-subscription-id": "str", }, - api_version="2024-11-01", ) ).result() # call '.result()' to poll until service return final result @@ -292,9 +272,18 @@ async def test_redis_begin_flush_cache(self, resource_group): await self.client.redis.begin_flush_cache( resource_group_name=resource_group.name, cache_name="str", - api_version="2024-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_redis_check_name_availability(self, resource_group): + response = await self.client.redis.check_name_availability( + parameters={"name": "str", "type": "str"}, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/redis/azure-mgmt-redis/pyproject.toml b/sdk/redis/azure-mgmt-redis/pyproject.toml index 540da07d41af..31885f75ad51 100644 --- a/sdk/redis/azure-mgmt-redis/pyproject.toml +++ b/sdk/redis/azure-mgmt-redis/pyproject.toml @@ -1,6 +1,87 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-redis" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Redis 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.redis._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-redis" +package_nspkg = "azure-mgmt-nspkg" +package_pprint_name = "Redis Cache Management" +package_doc_id = "redis" +is_stable = false +is_arm = true +sample_link = "" +title = "RedisManagementClient" +need_msrestazure = false +need_azuremgmtcore = true +exclude_folders = "" diff --git a/sdk/redis/azure-mgmt-redis/sdk_packaging.toml b/sdk/redis/azure-mgmt-redis/sdk_packaging.toml deleted file mode 100644 index 406e718c99a4..000000000000 --- a/sdk/redis/azure-mgmt-redis/sdk_packaging.toml +++ /dev/null @@ -1,9 +0,0 @@ -[packaging] -package_name = "azure-mgmt-redis" -package_nspkg = "azure-mgmt-nspkg" -package_pprint_name = "Redis Cache Management" -package_doc_id = "redis" -is_stable = true -is_arm = true -sample_link = "" -title = "RedisManagementClient" diff --git a/sdk/redis/azure-mgmt-redis/setup.py b/sdk/redis/azure-mgmt-redis/setup.py deleted file mode 100644 index e673ef0b9339..000000000000 --- a/sdk/redis/azure-mgmt-redis/setup.py +++ /dev/null @@ -1,83 +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-redis" -PACKAGE_PPRINT_NAME = "Redis Cache Management" - -# 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 :: 5 - Production/Stable", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "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=[ - "isodate>=0.6.1", - "typing-extensions>=4.6.0", - "azure-common>=1.1", - "azure-mgmt-core>=1.3.2", - ], - python_requires=">=3.8", -) diff --git a/sdk/redis/azure-mgmt-redis/tests/disable_test_cli_mgmt_redis.py b/sdk/redis/azure-mgmt-redis/tests/disable_test_cli_mgmt_redis.py deleted file mode 100644 index d054a0a7dcda..000000000000 --- a/sdk/redis/azure-mgmt-redis/tests/disable_test_cli_mgmt_redis.py +++ /dev/null @@ -1,282 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - - -# TEST SCENARIO COVERAGE -# ---------------------- -# Methods Total : 26 -# Methods Covered : 26 -# Examples Total : 26 -# Examples Tested : 20 -# Coverage % : 77 -# ---------------------- - -# Current Operation Coverage: -# Operations: 1/1 -# Redis: 10/13 -# FirewallRules: 4/4 -# PatchSchedules: 4/4 -# LinkedServer: 1/4 - -import time -import unittest - -import azure.mgmt.redis -from devtools_testutils import AzureMgmtTestCase, RandomNameResourceGroupPreparer - -AZURE_LOCATION = "eastus" - - -class MgmtRedisTest(AzureMgmtTestCase): - - def setUp(self): - super(MgmtRedisTest, self).setUp() - self.mgmt_client = self.create_mgmt_client(azure.mgmt.redis.RedisManagementClient) - - if self.is_live: - from azure.mgmt.network import NetworkManagementClient - - self.network_client = self.create_mgmt_client(NetworkManagementClient) - - def create_virtual_network(self, group_name, location, network_name, subnet_name): - - azure_operation_poller = self.network_client.virtual_networks.begin_create_or_update( - group_name, - network_name, - {"location": location, "address_space": {"address_prefixes": ["10.0.0.0/16"]}}, - ) - result_create = azure_operation_poller.result() - - async_subnet_creation = self.network_client.subnets.begin_create_or_update( - group_name, network_name, subnet_name, {"address_prefix": "10.0.0.0/24"} - ) - subnet_info = async_subnet_creation.result() - - return subnet_info - - @unittest.skip("hard to test") - @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) - def test_redis(self, resource_group): - - # UNIQUE = resource_group.name[-4:] - SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID - TENANT_ID = self.settings.TENANT_ID - RESOURCE_GROUP = resource_group.name - NAME = "myosgkxy" - VIRTUAL_NETWORK_NAME = "myVirtualNetwork" - SUBNET_NAME = "mySubnet" - # CACHE_NAME = "myCache" - CACHE_NAME = NAME - RULE_NAME = "myRule" - DEFAULT = "default" - LINKED_SERVER_NAME = "myLinkedServer" - REDIS_NAME = "myRedis" - - if self.is_live: - self.create_virtual_network(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_NETWORK_NAME, SUBNET_NAME) - - # -------------------------------------------------------------------------- - # /Redis/put/RedisCacheCreate[put] - # -------------------------------------------------------------------------- - BODY = { - "location": AZURE_LOCATION, - "zones": ["1"], - "sku": {"name": "Premium", "family": "P", "capacity": "1"}, - "enable_non_ssl_port": True, - "shard_count": "2", - # "replicas_per_master": "2", - "redis_configuration": {"maxmemory-policy": "allkeys-lru"}, - "subnet_id": "/subscriptions/" - + SUBSCRIPTION_ID - + "/resourceGroups/" - + RESOURCE_GROUP - + "/providers/Microsoft.Network/virtualNetworks/" - + VIRTUAL_NETWORK_NAME - + "/subnets/" - + SUBNET_NAME, - "static_ip": "10.0.0.5", - "minimum_tls_version": "1.2", - } - result = self.mgmt_client.redis.begin_create(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) - result = result.result() - - # -------------------------------------------------------------------------- - # /PatchSchedules/put/RedisCachePatchSchedulesCreateOrUpdate[put] - # -------------------------------------------------------------------------- - BODY = { - "schedule_entries": [ - {"day_of_week": "Monday", "start_hour_utc": "12", "maintenance_window": "PT5H"}, - {"day_of_week": "Tuesday", "start_hour_utc": "12"}, - ] - } - result = self.mgmt_client.patch_schedules.create_or_update( - resource_group_name=RESOURCE_GROUP, name=NAME, default=DEFAULT, parameters=BODY - ) - - if self.is_live: - time.sleep(1800) - - # -------------------------------------------------------------------------- - # /FirewallRules/put/RedisCacheFirewallRuleCreate[put] - # -------------------------------------------------------------------------- - BODY = {"start_ip": "10.0.1.1", "end_ip": "10.0.1.4"} - result = self.mgmt_client.firewall_rules.create_or_update( - resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME, rule_name=RULE_NAME, parameters=BODY - ) - - # -------------------------------------------------------------------------- - # /LinkedServer/put/LinkedServer_Create[put] - # -------------------------------------------------------------------------- - BODY = { - "linked_redis_cache_id": "/subscriptions/" - + SUBSCRIPTION_ID - + "/resourceGroups/" - + RESOURCE_GROUP - + "/providers/Microsoft.Cache/Redis/" - + REDIS_NAME, - "linked_redis_cache_location": "West US", - "server_role": "Secondary", - } - # result = self.mgmt_client.linked_server.begin_create(resource_group_name=RESOURCE_GROUP, name=NAME, linked_server_name=LINKED_SERVER_NAME, parameters=BODY) - # result = result.result() - - # -------------------------------------------------------------------------- - # /LinkedServer/get/LinkedServer_Get[get] - # -------------------------------------------------------------------------- - # result = self.mgmt_client.linked_server.get(resource_group_name=RESOURCE_GROUP, name=NAME, linked_server_name=LINKED_SERVER_NAME) - - # -------------------------------------------------------------------------- - # /FirewallRules/get/RedisCacheFirewallRuleGet[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.firewall_rules.get( - resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME, rule_name=RULE_NAME - ) - - # -------------------------------------------------------------------------- - # /PatchSchedules/get/RedisCachePatchSchedulesGet[get] - # -------------------------------------------------------------------------- - # result = self.mgmt_client.patch_schedules.get(resource_group_name=RESOURCE_GROUP, name=NAME, default=DEFAULT) - - # -------------------------------------------------------------------------- - # /Redis/get/RedisCacheGet[get] - # -------------------------------------------------------------------------- - # result = self.mgmt_client.redis.list_upgrade_notifications(resource_group_name=RESOURCE_GROUP, name=NAME, history="5000") - - # -------------------------------------------------------------------------- - # /PatchSchedules/get/RedisCachePatchSchedulesList[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.patch_schedules.list_by_redis_resource( - resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME - ) - - # -------------------------------------------------------------------------- - # /FirewallRules/get/RedisCacheFirewallRulesList[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.firewall_rules.list_by_redis_resource( - resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME - ) - - # -------------------------------------------------------------------------- - # /LinkedServer/get/LinkedServer_List[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.linked_server.list(resource_group_name=RESOURCE_GROUP, name=NAME) - - # -------------------------------------------------------------------------- - # /Redis/get/RedisCacheGet[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.redis.get(resource_group_name=RESOURCE_GROUP, name=NAME) - - # -------------------------------------------------------------------------- - # /Redis/get/RedisCacheListByResourceGroup[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.redis.list_by_resource_group(resource_group_name=RESOURCE_GROUP) - - # -------------------------------------------------------------------------- - # /Redis/get/RedisCacheList[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.redis.list() - - # -------------------------------------------------------------------------- - # /Operations/get/Operations_List[get] - # -------------------------------------------------------------------------- - result = self.mgmt_client.operations.list() - - # -------------------------------------------------------------------------- - # /Redis/post/RedisCacheRegenerateKey[post] - # -------------------------------------------------------------------------- - BODY = {"key_type": "Primary"} - result = self.mgmt_client.redis.regenerate_key(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) - - # -------------------------------------------------------------------------- - # /Redis/post/RedisCacheForceReboot[post] - # -------------------------------------------------------------------------- - BODY = {"shard_id": "0", "reboot_type": "AllNodes"} - result = self.mgmt_client.redis.force_reboot(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) - - # -------------------------------------------------------------------------- - # /Redis/post/RedisCacheListKeys[post] - # -------------------------------------------------------------------------- - result = self.mgmt_client.redis.list_keys(resource_group_name=RESOURCE_GROUP, name=NAME) - - # -------------------------------------------------------------------------- - # /Redis/post/RedisCacheImport[post] - # -------------------------------------------------------------------------- - BODY = {"format": "RDB", "files": ["http://fileuris.contoso.com/pathtofile1"]} - # result = self.mgmt_client.redis.begin_import_data(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) - # result = result.result() - - # -------------------------------------------------------------------------- - # /Redis/post/RedisCacheExport[post] - # -------------------------------------------------------------------------- - BODY = { - "format": "RDB", - "prefix": "datadump1", - "container": "https://contosostorage.blob.core.window.net/urltoBlobContainer?sasKeyParameters", - } - # result = self.mgmt_client.redis.begin_export_data(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) - # result = result.result() - - # -------------------------------------------------------------------------- - # /Redis/patch/RedisCacheUpdate[patch] - # -------------------------------------------------------------------------- - BODY = {"enable_non_ssl_port": True} - result = self.mgmt_client.redis.update(resource_group_name=RESOURCE_GROUP, name=NAME, parameters=BODY) - - # -------------------------------------------------------------------------- - # /Redis/post/RedisCacheList[post] - # -------------------------------------------------------------------------- - BODY = {"type": "Microsoft.Cache/Redis", "name": "cacheName"} - result = self.mgmt_client.redis.check_name_availability(parameters=BODY) - - # -------------------------------------------------------------------------- - # /LinkedServer/delete/LinkedServerDelete[delete] - # -------------------------------------------------------------------------- - # result = self.mgmt_client.linked_server.delete(resource_group_name=RESOURCE_GROUP, name=NAME, linked_server_name=LINKED_SERVER_NAME) - - # -------------------------------------------------------------------------- - # /FirewallRules/delete/RedisCacheFirewallRuleDelete[delete] - # -------------------------------------------------------------------------- - result = self.mgmt_client.firewall_rules.delete( - resource_group_name=RESOURCE_GROUP, cache_name=CACHE_NAME, rule_name=RULE_NAME - ) - - # -------------------------------------------------------------------------- - # /PatchSchedules/delete/RedisCachePatchSchedulesDelete[delete] - # -------------------------------------------------------------------------- - result = self.mgmt_client.patch_schedules.delete(resource_group_name=RESOURCE_GROUP, name=NAME, default=DEFAULT) - - # -------------------------------------------------------------------------- - # /Redis/delete/RedisCacheDelete[delete] - # -------------------------------------------------------------------------- - result = self.mgmt_client.redis.begin_delete(resource_group_name=RESOURCE_GROUP, name=NAME) - result = result.result() - - -# ------------------------------------------------------------------------------ -if __name__ == "__main__": - unittest.main() diff --git a/sdk/redis/azure-mgmt-redis/tsp-location.yaml b/sdk/redis/azure-mgmt-redis/tsp-location.yaml new file mode 100644 index 000000000000..d6168ca63ae6 --- /dev/null +++ b/sdk/redis/azure-mgmt-redis/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/redis/resource-manager/Microsoft.Cache/Redis +commit: 0ac0baaafaa117fd7296c0159ef2489d0461f86f +repo: Azure/azure-rest-api-specs +additionalDirectories: