diff --git a/sdk/eventgrid/azure-eventgrid/_meta.json b/sdk/eventgrid/azure-eventgrid/_meta.json new file mode 100644 index 000000000000..5fad186ee455 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "f69147628e524f70bdf7ada9a84461bfa546b5a5", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/eventgrid/Azure.Messaging.EventGrid", + "@azure-tools/typespec-python": "0.26.0" +} \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py index 7189e7b5a4f9..f3cd024d0f19 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py @@ -6,8 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import EventGridPublisherClient -from ._patch import EventGridConsumerClient +from ._client import EventGridPublisherClient +from ._client import EventGridConsumerClient from ._version import VERSION __version__ = VERSION diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py index c6ce28f47f9a..8d8cbffd0ab5 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py @@ -8,6 +8,7 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING, Union +from typing_extensions import Self from azure.core import PipelineClient from azure.core.credentials import AzureKeyCredential @@ -95,7 +96,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: def close(self) -> None: self._client.close() - def __enter__(self) -> "EventGridPublisherClient": + def __enter__(self) -> Self: self._client.__enter__() return self @@ -175,7 +176,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: def close(self) -> None: self._client.close() - def __enter__(self) -> "EventGridConsumerClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/__init__.py deleted file mode 100644 index 1dc3655a13bb..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/__init__.py +++ /dev/null @@ -1,19 +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. -# -------------------------------------------------------------------------- - -from ._publisher_client import EventGridPublisherClient -from ._event_mappings import SystemEventNames -from ._helpers import generate_sas -from ._models import EventGridEvent -from ._version import VERSION - -__all__ = [ - "EventGridPublisherClient", - "EventGridEvent", - "generate_sas", - "SystemEventNames", -] -__version__ = VERSION diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_constants.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_constants.py deleted file mode 100644 index c246323f9476..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_constants.py +++ /dev/null @@ -1,10 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -DEFAULT_EVENTGRID_SCOPE = "https://eventgrid.azure.net/.default" -EVENTGRID_KEY_HEADER = "aeg-sas-key" -EVENTGRID_TOKEN_HEADER = "aeg-sas-token" -DEFAULT_API_VERSION = "2018-01-01" -SAFE_ENCODE = "~()*!.'" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_event_mappings.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_event_mappings.py deleted file mode 100644 index 59fbfed265e6..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_event_mappings.py +++ /dev/null @@ -1,533 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. - -# THE VALUES IN THE ENUM ARE AUTO-GENERATED. DO NOT EDIT THIS MANUALLY. -# -------------------------------------------------------------------------------------------- -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -# pylint: disable=line-too-long -# pylint: disable=enum-must-be-uppercase -class SystemEventNames(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ - This enum represents the names of the various event types for the system events published to - Azure Event Grid. To check the list of recognizable system topics, - visit https://docs.microsoft.com/azure/event-grid/system-topics. - """ - - # These names at the top are 'corrected' aliases of duplicate values that appear below, which are - # deprecated but maintained for backwards compatibility. - AcsChatMemberAddedToThreadWithUserEventName = "Microsoft.Communication.ChatMemberAddedToThreadWithUser" - - ResourceWriteFailureEventName = "Microsoft.Resources.ResourceWriteFailure" - - IoTHubDeviceDeletedEventName = "Microsoft.Devices.DeviceDeleted" - - IoTHubDeviceDisconnectedEventName = "Microsoft.Devices.DeviceDisconnected" - - ResourceDeleteFailureEventName = "Microsoft.Resources.ResourceDeleteFailure" - - ResourceDeleteCancelEventName = "Microsoft.Resources.ResourceDeleteCancel" - - AcsChatThreadParticipantAddedEventName = "Microsoft.Communication.ChatThreadParticipantAdded" - - ResourceDeleteSuccessEventName = "Microsoft.Resources.ResourceDeleteSuccess" - - EventGridSubscriptionValidationEventName = "Microsoft.EventGrid.SubscriptionValidationEvent" - - ResourceWriteSuccessEventName = "Microsoft.Resources.ResourceWriteSuccess" - - ResourceActionSuccessEventName = "Microsoft.Resources.ResourceActionSuccess" - - ResourceWriteCancelEventName = "Microsoft.Resources.ResourceWriteCancel" - - ResourceActionFailureEventName = "Microsoft.Resources.ResourceActionFailure" - - AcsChatMemberRemovedFromThreadWithUserEventName = "Microsoft.Communication.ChatMemberRemovedFromThreadWithUser" - - IoTHubDeviceConnectedEventName = "Microsoft.Devices.DeviceConnected" - - EventGridSubscriptionDeletedEventName = "Microsoft.EventGrid.SubscriptionDeletedEvent" - - AcsChatThreadParticipantRemovedEventName = "Microsoft.Communication.ChatThreadParticipantRemoved" - - ResourceActionCancelEventName = "Microsoft.Resources.ResourceActionCancel" - - IoTHubDeviceCreatedEventName = "Microsoft.Devices.DeviceCreated" - - # Aliases end here - AcsAdvancedMessageDeliveryStatusUpdatedEventName = "Microsoft.Communication.AdvancedMessageDeliveryStatusUpdated" - - AcsAdvancedMessageReceivedEventName = "Microsoft.Communication.AdvancedMessageReceived" - - AcsChatMessageDeletedEventName = "Microsoft.Communication.ChatMessageDeleted" - - AcsChatMessageDeletedInThreadEventName = "Microsoft.Communication.ChatMessageDeletedInThread" - - AcsChatMessageEditedEventName = "Microsoft.Communication.ChatMessageEdited" - - AcsChatMessageEditedInThreadEventName = "Microsoft.Communication.ChatMessageEditedInThread" - - AcsChatMessageReceivedEventName = "Microsoft.Communication.ChatMessageReceived" - - AcsChatMessageReceivedInThreadEventName = "Microsoft.Communication.ChatMessageReceivedInThread" - - AcsChatParticipantAddedToThreadEventName = "Microsoft.Communication.ChatThreadParticipantAdded" - - AcsChatParticipantAddedToThreadWithUserEventName = "Microsoft.Communication.ChatParticipantAddedToThreadWithUser" - - AcsChatParticipantRemovedFromThreadEventName = "Microsoft.Communication.ChatThreadParticipantRemoved" - - AcsChatParticipantRemovedFromThreadWithUserEventName = ( - "Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser" - ) - - AcsChatThreadCreatedEventName = "Microsoft.Communication.ChatThreadCreated" - - AcsChatThreadCreatedWithUserEventName = "Microsoft.Communication.ChatThreadCreatedWithUser" - - AcsChatThreadDeletedEventName = "Microsoft.Communication.ChatThreadDeleted" - - AcsChatThreadPropertiesUpdatedEventName = "Microsoft.Communication.ChatThreadPropertiesUpdated" - - AcsChatThreadPropertiesUpdatedPerUserEventName = "Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser" - - AcsChatThreadWithUserDeletedEventName = "Microsoft.Communication.ChatThreadWithUserDeleted" - - AcsEmailDeliveryReportReceivedEventName = "Microsoft.Communication.EmailDeliveryReportReceived" - - AcsEmailEngagementTrackingReportReceivedEventName = "Microsoft.Communication.EmailEngagementTrackingReportReceived" - - AcsIncomingCallEventName = "Microsoft.Communication.IncomingCall" - - AcsRecordingFileStatusUpdatedEventName = "Microsoft.Communication.RecordingFileStatusUpdated" - - AcsRouterJobCancelledEventName = "Microsoft.Communication.RouterJobCancelled" - - AcsRouterJobClassificationFailedEventName = "Microsoft.Communication.RouterJobClassificationFailed" - - AcsRouterJobClassifiedEventName = "Microsoft.Communication.RouterJobClassified" - - AcsRouterJobClosedEventName = "Microsoft.Communication.RouterJobClosed" - - AcsRouterJobCompletedEventName = "Microsoft.Communication.RouterJobCompleted" - - AcsRouterJobDeletedEventName = "Microsoft.Communication.RouterJobDeleted" - - AcsRouterJobExceptionTriggeredEventName = "Microsoft.Communication.RouterJobExceptionTriggered" - - AcsRouterJobQueuedEventName = "Microsoft.Communication.RouterJobQueued" - - AcsRouterJobReceivedEventName = "Microsoft.Communication.RouterJobReceived" - - AcsRouterJobSchedulingFailedEventName = "Microsoft.Communication.RouterJobSchedulingFailed" - - AcsRouterJobUnassignedEventName = "Microsoft.Communication.RouterJobUnassigned" - - AcsRouterJobWaitingForActivationEventName = "Microsoft.Communication.RouterJobWaitingForActivation" - - AcsRouterJobWorkerSelectorsExpiredEventName = "Microsoft.Communication.RouterJobWorkerSelectorsExpired" - - AcsRouterWorkerDeletedEventName = "Microsoft.Communication.RouterWorkerDeleted" - - AcsRouterWorkerDeregisteredEventName = "Microsoft.Communication.RouterWorkerDeregistered" - - AcsRouterWorkerOfferAcceptedEventName = "Microsoft.Communication.RouterWorkerOfferAccepted" - - AcsRouterWorkerOfferDeclinedEventName = "Microsoft.Communication.RouterWorkerOfferDeclined" - - AcsRouterWorkerOfferExpiredEventName = "Microsoft.Communication.RouterWorkerOfferExpired" - - AcsRouterWorkerOfferIssuedEventName = "Microsoft.Communication.RouterWorkerOfferIssued" - - AcsRouterWorkerOfferRevokedEventName = "Microsoft.Communication.RouterWorkerOfferRevoked" - - AcsRouterWorkerRegisteredEventName = "Microsoft.Communication.RouterWorkerRegistered" - - AcsRouterWorkerUpdatedEventName = "Microsoft.Communication.RouterWorkerUpdated" - - AcsSmsDeliveryReportReceivedEventName = "Microsoft.Communication.SMSDeliveryReportReceived" - - AcsSmsReceivedEventName = "Microsoft.Communication.SMSReceived" - - AcsUserDisconnectedEventName = "Microsoft.Communication.UserDisconnected" - - ApiCenterApiDefinitionAddedEventName = "Microsoft.ApiCenter.ApiDefinitionAdded" - - ApiCenterApiDefinitionUpdatedEventName = "Microsoft.ApiCenter.ApiDefinitionUpdated" - - ApiManagementApiCreatedEventName = "Microsoft.ApiManagement.APICreated" - - ApiManagementApiDeletedEventName = "Microsoft.ApiManagement.APIDeleted" - - ApiManagementApiReleaseCreatedEventName = "Microsoft.ApiManagement.APIReleaseCreated" - - ApiManagementApiReleaseDeletedEventName = "Microsoft.ApiManagement.APIReleaseDeleted" - - ApiManagementApiReleaseUpdatedEventName = "Microsoft.ApiManagement.APIReleaseUpdated" - - ApiManagementApiUpdatedEventName = "Microsoft.ApiManagement.APIUpdated" - - ApiManagementGatewayApiAddedEventName = "Microsoft.ApiManagement.GatewayAPIAdded" - - ApiManagementGatewayApiRemovedEventName = "Microsoft.ApiManagement.GatewayAPIRemoved" - - ApiManagementGatewayCertificateAuthorityCreatedEventName = ( - "Microsoft.ApiManagement.GatewayCertificateAuthorityCreated" - ) - - ApiManagementGatewayCertificateAuthorityDeletedEventName = ( - "Microsoft.ApiManagement.GatewayCertificateAuthorityDeleted" - ) - - ApiManagementGatewayCertificateAuthorityUpdatedEventName = ( - "Microsoft.ApiManagement.GatewayCertificateAuthorityUpdated" - ) - - ApiManagementGatewayCreatedEventName = "Microsoft.ApiManagement.GatewayCreated" - - ApiManagementGatewayDeletedEventName = "Microsoft.ApiManagement.GatewayDeleted" - - ApiManagementGatewayHostnameConfigurationCreatedEventName = ( - "Microsoft.ApiManagement.GatewayHostnameConfigurationCreated" - ) - - ApiManagementGatewayHostnameConfigurationDeletedEventName = ( - "Microsoft.ApiManagement.GatewayHostnameConfigurationDeleted" - ) - - ApiManagementGatewayHostnameConfigurationUpdatedEventName = ( - "Microsoft.ApiManagement.GatewayHostnameConfigurationUpdated" - ) - - ApiManagementGatewayUpdatedEventName = "Microsoft.ApiManagement.GatewayUpdated" - - ApiManagementProductCreatedEventName = "Microsoft.ApiManagement.ProductCreated" - - ApiManagementProductDeletedEventName = "Microsoft.ApiManagement.ProductDeleted" - - ApiManagementProductUpdatedEventName = "Microsoft.ApiManagement.ProductUpdated" - - ApiManagementSubscriptionCreatedEventName = "Microsoft.ApiManagement.SubscriptionCreated" - - ApiManagementSubscriptionDeletedEventName = "Microsoft.ApiManagement.SubscriptionDeleted" - - ApiManagementSubscriptionUpdatedEventName = "Microsoft.ApiManagement.SubscriptionUpdated" - - ApiManagementUserCreatedEventName = "Microsoft.ApiManagement.UserCreated" - - ApiManagementUserDeletedEventName = "Microsoft.ApiManagement.UserDeleted" - - ApiManagementUserUpdatedEventName = "Microsoft.ApiManagement.UserUpdated" - - AppConfigurationKeyValueDeletedEventName = "Microsoft.AppConfiguration.KeyValueDeleted" - - AppConfigurationKeyValueModifiedEventName = "Microsoft.AppConfiguration.KeyValueModified" - - AppConfigurationSnapshotCreatedEventName = "Microsoft.AppConfiguration.SnapshotCreated" - - AppConfigurationSnapshotModifiedEventName = "Microsoft.AppConfiguration.SnapshotModified" - - AvsClusterCreatedEventName = "Microsoft.AVS.ClusterCreated" - - AvsClusterDeletedEventName = "Microsoft.AVS.ClusterDeleted" - - AvsClusterFailedEventName = "Microsoft.AVS.ClusterFailed" - - AvsClusterUpdatedEventName = "Microsoft.AVS.ClusterUpdated" - - AvsClusterUpdatingEventName = "Microsoft.AVS.ClusterUpdating" - - AvsPrivateCloudFailedEventName = "Microsoft.AVS.PrivateCloudFailed" - - AvsPrivateCloudUpdatedEventName = "Microsoft.AVS.PrivateCloudUpdated" - - AvsPrivateCloudUpdatingEventName = "Microsoft.AVS.PrivateCloudUpdating" - - AvsScriptExecutionCancelledEventName = "Microsoft.AVS.ScriptExecutionCancelled" - - AvsScriptExecutionFailedEventName = "Microsoft.AVS.ScriptExecutionFailed" - - AvsScriptExecutionFinishedEventName = "Microsoft.AVS.ScriptExecutionFinished" - - AvsScriptExecutionStartedEventName = "Microsoft.AVS.ScriptExecutionStarted" - - ContainerRegistryChartDeletedEventName = "Microsoft.ContainerRegistry.ChartDeleted" - - ContainerRegistryChartPushedEventName = "Microsoft.ContainerRegistry.ChartPushed" - - ContainerRegistryImageDeletedEventName = "Microsoft.ContainerRegistry.ImageDeleted" - - ContainerRegistryImagePushedEventName = "Microsoft.ContainerRegistry.ImagePushed" - - ContainerServiceClusterSupportEndedEventName = "Microsoft.ContainerService.ClusterSupportEnded" - - ContainerServiceClusterSupportEndingEventName = "Microsoft.ContainerService.ClusterSupportEnding" - - ContainerServiceNewKubernetesVersionAvailableEventName = "Microsoft.ContainerService.NewKubernetesVersionAvailable" - - ContainerServiceNodePoolRollingFailedEventName = "Microsoft.ContainerService.NodePoolRollingFailed" - - ContainerServiceNodePoolRollingStartedEventName = "Microsoft.ContainerService.NodePoolRollingStarted" - - ContainerServiceNodePoolRollingSucceededEventName = "Microsoft.ContainerService.NodePoolRollingSucceeded" - - DataBoxCopyCompletedEventName = "Microsoft.DataBox.CopyCompleted" - - DataBoxCopyStartedEventName = "Microsoft.DataBox.CopyStarted" - - DataBoxOrderCompletedEventName = "Microsoft.DataBox.OrderCompleted" - - EventGridMQTTClientCreatedOrUpdatedEventName = "Microsoft.EventGrid.MQTTClientCreatedOrUpdated" - - EventGridMQTTClientDeletedEventName = "Microsoft.EventGrid.MQTTClientDeleted" - - EventGridMQTTClientSessionConnectedEventName = "Microsoft.EventGrid.MQTTClientSessionConnected" - - EventGridMQTTClientSessionDisconnectedEventName = "Microsoft.EventGrid.MQTTClientSessionDisconnected" - - EventHubCaptureFileCreatedEventName = "Microsoft.EventHub.CaptureFileCreated" - - HealthcareDicomImageCreatedEventName = "Microsoft.HealthcareApis.DicomImageCreated" - - HealthcareDicomImageDeletedEventName = "Microsoft.HealthcareApis.DicomImageDeleted" - - HealthcareDicomImageUpdatedEventName = "Microsoft.HealthcareApis.DicomImageUpdated" - - HealthcareFhirResourceCreatedEventName = "Microsoft.HealthcareApis.FhirResourceCreated" - - HealthcareFhirResourceDeletedEventName = "Microsoft.HealthcareApis.FhirResourceDeleted" - - HealthcareFhirResourceUpdatedEventName = "Microsoft.HealthcareApis.FhirResourceUpdated" - - IotHubDeviceConnectedEventName = "Microsoft.Devices.DeviceConnected" - - IotHubDeviceCreatedEventName = "Microsoft.Devices.DeviceCreated" - - IotHubDeviceDeletedEventName = "Microsoft.Devices.DeviceDeleted" - - IotHubDeviceDisconnectedEventName = "Microsoft.Devices.DeviceDisconnected" - - IotHubDeviceTelemetryEventName = "Microsoft.Devices.DeviceTelemetry" - - KeyVaultCertificateExpiredEventName = "Microsoft.KeyVault.CertificateExpired" - - KeyVaultCertificateNearExpiryEventName = "Microsoft.KeyVault.CertificateNearExpiry" - - KeyVaultCertificateNewVersionCreatedEventName = "Microsoft.KeyVault.CertificateNewVersionCreated" - - KeyVaultKeyExpiredEventName = "Microsoft.KeyVault.KeyExpired" - - KeyVaultKeyNearExpiryEventName = "Microsoft.KeyVault.KeyNearExpiry" - - KeyVaultKeyNewVersionCreatedEventName = "Microsoft.KeyVault.KeyNewVersionCreated" - - KeyVaultSecretExpiredEventName = "Microsoft.KeyVault.SecretExpired" - - KeyVaultSecretNearExpiryEventName = "Microsoft.KeyVault.SecretNearExpiry" - - KeyVaultSecretNewVersionCreatedEventName = "Microsoft.KeyVault.SecretNewVersionCreated" - - KeyVaultVaultAccessPolicyChangedEventName = "Microsoft.KeyVault.VaultAccessPolicyChanged" - - MachineLearningServicesDatasetDriftDetectedEventName = "Microsoft.MachineLearningServices.DatasetDriftDetected" - - MachineLearningServicesModelDeployedEventName = "Microsoft.MachineLearningServices.ModelDeployed" - - MachineLearningServicesModelRegisteredEventName = "Microsoft.MachineLearningServices.ModelRegistered" - - MachineLearningServicesRunCompletedEventName = "Microsoft.MachineLearningServices.RunCompleted" - - MachineLearningServicesRunStatusChangedEventName = "Microsoft.MachineLearningServices.RunStatusChanged" - - MapsGeofenceEnteredEventName = "Microsoft.Maps.GeofenceEntered" - - MapsGeofenceExitedEventName = "Microsoft.Maps.GeofenceExited" - - MapsGeofenceResultEventName = "Microsoft.Maps.GeofenceResult" - - MediaJobCanceledEventName = "Microsoft.Media.JobCanceled" - - MediaJobCancelingEventName = "Microsoft.Media.JobCanceling" - - MediaJobErroredEventName = "Microsoft.Media.JobErrored" - - MediaJobFinishedEventName = "Microsoft.Media.JobFinished" - - MediaJobOutputCanceledEventName = "Microsoft.Media.JobOutputCanceled" - - MediaJobOutputCancelingEventName = "Microsoft.Media.JobOutputCanceling" - - MediaJobOutputErroredEventName = "Microsoft.Media.JobOutputErrored" - - MediaJobOutputFinishedEventName = "Microsoft.Media.JobOutputFinished" - - MediaJobOutputProcessingEventName = "Microsoft.Media.JobOutputProcessing" - - MediaJobOutputProgressEventName = "Microsoft.Media.JobOutputProgress" - - MediaJobOutputScheduledEventName = "Microsoft.Media.JobOutputScheduled" - - MediaJobOutputStateChangeEventName = "Microsoft.Media.JobOutputStateChange" - - MediaJobProcessingEventName = "Microsoft.Media.JobProcessing" - - MediaJobScheduledEventName = "Microsoft.Media.JobScheduled" - - MediaJobStateChangeEventName = "Microsoft.Media.JobStateChange" - - MediaLiveEventChannelArchiveHeartbeatEventName = "Microsoft.Media.LiveEventChannelArchiveHeartbeat" - - MediaLiveEventConnectionRejectedEventName = "Microsoft.Media.LiveEventConnectionRejected" - - MediaLiveEventEncoderConnectedEventName = "Microsoft.Media.LiveEventEncoderConnected" - - MediaLiveEventEncoderDisconnectedEventName = "Microsoft.Media.LiveEventEncoderDisconnected" - - MediaLiveEventIncomingDataChunkDroppedEventName = "Microsoft.Media.LiveEventIncomingDataChunkDropped" - - MediaLiveEventIncomingStreamReceivedEventName = "Microsoft.Media.LiveEventIncomingStreamReceived" - - MediaLiveEventIncomingStreamsOutOfSyncEventName = "Microsoft.Media.LiveEventIncomingStreamsOutOfSync" - - MediaLiveEventIncomingVideoStreamsOutOfSyncEventName = "Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync" - - MediaLiveEventIngestHeartbeatEventName = "Microsoft.Media.LiveEventIngestHeartbeat" - - MediaLiveEventTrackDiscontinuityDetectedEventName = "Microsoft.Media.LiveEventTrackDiscontinuityDetected" - - PolicyInsightsPolicyStateChangedEventName = "Microsoft.PolicyInsights.PolicyStateChanged" - - PolicyInsightsPolicyStateCreatedEventName = "Microsoft.PolicyInsights.PolicyStateCreated" - - PolicyInsightsPolicyStateDeletedEventName = "Microsoft.PolicyInsights.PolicyStateDeleted" - - RedisExportRDBCompletedEventName = "Microsoft.Cache.ExportRDBCompleted" - - RedisImportRDBCompletedEventName = "Microsoft.Cache.ImportRDBCompleted" - - RedisPatchingCompletedEventName = "Microsoft.Cache.PatchingCompleted" - - RedisScalingCompletedEventName = "Microsoft.Cache.ScalingCompleted" - - ResourceActionCancelName = "Microsoft.Resources.ResourceActionCancel" - - ResourceActionFailureName = "Microsoft.Resources.ResourceActionFailure" - - ResourceActionSuccessName = "Microsoft.Resources.ResourceActionSuccess" - - ResourceDeleteCancelName = "Microsoft.Resources.ResourceDeleteCancel" - - ResourceDeleteFailureName = "Microsoft.Resources.ResourceDeleteFailure" - - ResourceDeleteSuccessName = "Microsoft.Resources.ResourceDeleteSuccess" - - ResourceNotificationsHealthResourcesAnnotatedEventName = ( - "Microsoft.ResourceNotifications.HealthResources.ResourceAnnotated" - ) - - ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventName = ( - "Microsoft.ResourceNotifications.HealthResources.AvailabilityStatusChanged" - ) - - ResourceNotificationsResourceManagementCreatedOrUpdatedEventName = ( - "Microsoft.ResourceNotifications.Resources.CreatedOrUpdated" - ) - - ResourceNotificationsResourceManagementDeletedEventName = "Microsoft.ResourceNotifications.Resources.Deleted" - - ResourceWriteCancelName = "Microsoft.Resources.ResourceWriteCancel" - - ResourceWriteFailureName = "Microsoft.Resources.ResourceWriteFailure" - - ResourceWriteSuccessName = "Microsoft.Resources.ResourceWriteSuccess" - - ServiceBusActiveMessagesAvailablePeriodicNotificationsEventName = ( - "Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications" - ) - - ServiceBusActiveMessagesAvailableWithNoListenersEventName = ( - "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners" - ) - - ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventName = ( - "Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications" - ) - - ServiceBusDeadletterMessagesAvailableWithNoListenersEventName = ( - "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners" - ) - - SignalRServiceClientConnectionConnectedEventName = "Microsoft.SignalRService.ClientConnectionConnected" - - SignalRServiceClientConnectionDisconnectedEventName = "Microsoft.SignalRService.ClientConnectionDisconnected" - - StorageAsyncOperationInitiatedEventName = "Microsoft.Storage.AsyncOperationInitiated" - - StorageBlobCreatedEventName = "Microsoft.Storage.BlobCreated" - - StorageBlobDeletedEventName = "Microsoft.Storage.BlobDeleted" - - StorageBlobInventoryPolicyCompletedEventName = "Microsoft.Storage.BlobInventoryPolicyCompleted" - - StorageBlobRenamedEventName = "Microsoft.Storage.BlobRenamed" - - StorageBlobTierChangedEventName = "Microsoft.Storage.BlobTierChanged" - - StorageDirectoryCreatedEventName = "Microsoft.Storage.DirectoryCreated" - - StorageDirectoryDeletedEventName = "Microsoft.Storage.DirectoryDeleted" - - StorageDirectoryRenamedEventName = "Microsoft.Storage.DirectoryRenamed" - - StorageLifecyclePolicyCompletedEventName = "Microsoft.Storage.LifecyclePolicyCompleted" - - StorageTaskAssignmentCompletedEventName = "Microsoft.Storage.StorageTaskAssignmentCompleted" - - StorageTaskAssignmentQueuedEventName = "Microsoft.Storage.StorageTaskAssignmentQueued" - - StorageTaskCompletedEventName = "Microsoft.Storage.StorageTaskCompleted" - - StorageTaskQueuedEventName = "Microsoft.Storage.StorageTaskQueued" - - SubscriptionDeletedEventName = "Microsoft.EventGrid.SubscriptionDeletedEvent" - - SubscriptionValidationEventName = "Microsoft.EventGrid.SubscriptionValidationEvent" - - WebAppServicePlanUpdatedEventName = "Microsoft.Web.AppServicePlanUpdated" - - WebAppUpdatedEventName = "Microsoft.Web.AppUpdated" - - WebBackupOperationCompletedEventName = "Microsoft.Web.BackupOperationCompleted" - - WebBackupOperationFailedEventName = "Microsoft.Web.BackupOperationFailed" - - WebBackupOperationStartedEventName = "Microsoft.Web.BackupOperationStarted" - - WebRestoreOperationCompletedEventName = "Microsoft.Web.RestoreOperationCompleted" - - WebRestoreOperationFailedEventName = "Microsoft.Web.RestoreOperationFailed" - - WebRestoreOperationStartedEventName = "Microsoft.Web.RestoreOperationStarted" - - WebSlotSwapCompletedEventName = "Microsoft.Web.SlotSwapCompleted" - - WebSlotSwapFailedEventName = "Microsoft.Web.SlotSwapFailed" - - WebSlotSwapStartedEventName = "Microsoft.Web.SlotSwapStarted" - - WebSlotSwapWithPreviewCancelledEventName = "Microsoft.Web.SlotSwapWithPreviewCancelled" - - WebSlotSwapWithPreviewStartedEventName = "Microsoft.Web.SlotSwapWithPreviewStarted" - - ContainerRegistryArtifactEventName = "Microsoft.AppConfiguration.KeyValueModified" - - KeyVaultAccessPolicyChangedEventName = "Microsoft.KeyVault.VaultAccessPolicyChanged" - - ContainerRegistryEventName = "Microsoft.ContainerRegistry.ChartPushed" - - ServiceBusDeadletterMessagesAvailableWithNoListenerEventName = ( - "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners" - ) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/__init__.py deleted file mode 100644 index 802c5324f641..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/__init__.py +++ /dev/null @@ -1,23 +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 ._client import EventGridPublisherClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "EventGridPublisherClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_client.py deleted file mode 100644 index f3ad2db7363a..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_client.py +++ /dev/null @@ -1,71 +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 copy import deepcopy -from typing import Any - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from . import models as _models -from ._configuration import EventGridPublisherClientConfiguration -from ._operations import EventGridPublisherClientOperationsMixin -from ._serialization import Deserializer, Serializer - - -class EventGridPublisherClient( - EventGridPublisherClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword - """EventGrid Python Publisher Client. - - :keyword api_version: Api Version. Default value is "2018-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, **kwargs: Any) -> None: # pylint: disable=missing-client-constructor-parameter-credential - _endpoint = "https://{topicHostname}" - self._config = EventGridPublisherClientConfiguration(**kwargs) - self._client: PipelineClient = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> "EventGridPublisherClient": - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_configuration.py deleted file mode 100644 index d105970e51f9..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_configuration.py +++ /dev/null @@ -1,51 +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 - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - -VERSION = "unknown" - - -class EventGridPublisherClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for EventGridPublisherClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :keyword api_version: Api Version. Default value is "2018-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, **kwargs: Any) -> None: - super(EventGridPublisherClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", "2018-01-01") - - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "eventgridpublisherclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/__init__.py deleted file mode 100644 index 2223086fe7d0..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/__init__.py +++ /dev/null @@ -1,19 +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 ._operations import EventGridPublisherClientOperationsMixin - -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "EventGridPublisherClientOperationsMixin", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_operations.py deleted file mode 100644 index 0ba43ddc6003..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_operations/_operations.py +++ /dev/null @@ -1,401 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._serialization import Serializer -from .._vendor import EventGridPublisherClientMixinABC - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_event_grid_publisher_publish_events_request(**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: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) - # Construct URL - _url = "/api/events" - - # 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_event_grid_publisher_publish_cloud_event_events_request( - *, json: List[_models.CloudEvent], **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: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) - # Construct URL - _url = "/api/events" - - # 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, json=json, **kwargs) - - -def build_event_grid_publisher_publish_custom_event_events_request( - **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: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) - # Construct URL - _url = "/api/events" - - # 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) - - -class EventGridPublisherClientOperationsMixin(EventGridPublisherClientMixinABC): - @overload - def publish_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: List[_models.EventGridEvent], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: list[~event_grid_publisher_client.models.EventGridEvent] - :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 publish_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: IO, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: IO - :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 publish_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: Union[List[_models.EventGridEvent], IO], - **kwargs: Any, - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Is either a [EventGridEvent] - type or a IO type. Required. - :type events: list[~event_grid_publisher_client.models.EventGridEvent] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = 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" - _json = None - _content = None - if isinstance(events, (IO, bytes)): - _content = events - else: - _json = self._serialize.body(events, "[EventGridEvent]") - - request = build_event_grid_publisher_publish_events_request( - content_type=content_type, - api_version=self._config.api_version, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) - - @distributed_trace - def publish_cloud_event_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: List[_models.CloudEvent], **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: list[~event_grid_publisher_client.models.CloudEvent] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: str = kwargs.pop( - "content_type", - _headers.pop("Content-Type", "application/cloudevents-batch+json; charset=utf-8"), - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - _json = self._serialize.body(events, "[CloudEvent]") - - request = build_event_grid_publisher_publish_cloud_event_events_request( - content_type=content_type, - api_version=self._config.api_version, - json=_json, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) - - @overload - def publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: List[JSON], - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: list[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 publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: IO, - *, - content_type: str = "application/json", - **kwargs: Any, - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: IO - :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 publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: Union[List[JSON], IO], **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Is either a [JSON] type or a - IO type. Required. - :type events: list[JSON] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = 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" - _json = None - _content = None - if isinstance(events, (IO, bytes)): - _content = events - else: - _json = self._serialize.body(events, "[object]") - - request = build_event_grid_publisher_publish_custom_event_events_request( - content_type=content_type, - api_version=self._config.api_version, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_serialization.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_serialization.py deleted file mode 100644 index 1e7a11b1d256..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_serialization.py +++ /dev/null @@ -1,2027 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Dict, - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - TypeVar, - MutableMapping, - Type, - List, - Mapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore - -from azure.core.exceptions import ( - DeserializationError, - SerializationError, - raise_with_traceback, -) -from azure.core.serialization import NULL as AzureCoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -ModelType = TypeVar("ModelType", bound="Model") -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Dict[str, Any] = {} - for k in kwargs: - if k not in self._attribute_map: - _LOGGER.warning( - "%s is not a known attribute of class %s and will be ignored", - k, - self.__class__, - ) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning( - "Readonly attribute %s will be ignored in class %s", - k, - self.__class__, - ) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node.""" - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node( - xml_map.get("name", cls.__name__), - xml_map.get("prefix", None), - xml_map.get("ns", None), - ) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: - """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 - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) - - @classmethod - def from_dict( - cls: Type[ModelType], - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> ModelType: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises: DeserializationError if something went wrong - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning( - "Discriminator %s is absent or null, use base class %s.", - subtype_key, - cls.__name__, - ) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - """ - return key.replace("\\.", ".") - - -class Serializer(object): - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is AzureCoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node( - node_name, - xml_desc.get("prefix", None), - xml_desc.get("ns", None), - ) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, - utc.tm_mon, - utc.tm_mday, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(List[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map # type: ignore - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", - exc_info=True, - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning( - "Deserializer is not able to find %s as valid enum in %s", - data, - enum_obj, - ) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_vendor.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_vendor.py deleted file mode 100644 index 46152be31b39..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/_vendor.py +++ /dev/null @@ -1,26 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import TYPE_CHECKING - -from ._configuration import EventGridPublisherClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import PipelineClient - - from ._serialization import Deserializer, Serializer - - -class EventGridPublisherClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "PipelineClient" - _config: EventGridPublisherClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/__init__.py deleted file mode 100644 index 802c5324f641..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/__init__.py +++ /dev/null @@ -1,23 +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 ._client import EventGridPublisherClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "EventGridPublisherClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_client.py deleted file mode 100644 index f81ce4181ad6..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_client.py +++ /dev/null @@ -1,71 +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 copy import deepcopy -from typing import Any, Awaitable - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .. import models as _models -from .._serialization import Deserializer, Serializer -from ._configuration import EventGridPublisherClientConfiguration -from ._operations import EventGridPublisherClientOperationsMixin - - -class EventGridPublisherClient( - EventGridPublisherClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword - """EventGrid Python Publisher Client. - - :keyword api_version: Api Version. Default value is "2018-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, **kwargs: Any) -> None: # pylint: disable=missing-client-constructor-parameter-credential - _endpoint = "https://{topicHostname}" - self._config = EventGridPublisherClientConfiguration(**kwargs) - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "EventGridPublisherClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_configuration.py deleted file mode 100644 index 52c2f3551ad7..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_configuration.py +++ /dev/null @@ -1,51 +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 - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - -VERSION = "unknown" - - -class EventGridPublisherClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for EventGridPublisherClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :keyword api_version: Api Version. Default value is "2018-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, **kwargs: Any) -> None: - super(EventGridPublisherClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", "2018-01-01") - - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "eventgridpublisherclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/__init__.py deleted file mode 100644 index 2223086fe7d0..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/__init__.py +++ /dev/null @@ -1,19 +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 ._operations import EventGridPublisherClientOperationsMixin - -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "EventGridPublisherClientOperationsMixin", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_operations.py deleted file mode 100644 index ba6dc3ff67e5..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_operations/_operations.py +++ /dev/null @@ -1,319 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload - -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._operations._operations import ( - build_event_grid_publisher_publish_cloud_event_events_request, - build_event_grid_publisher_publish_custom_event_events_request, - build_event_grid_publisher_publish_events_request, -) -from .._vendor import EventGridPublisherClientMixinABC - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - - -class EventGridPublisherClientOperationsMixin(EventGridPublisherClientMixinABC): - @overload - async def publish_events( # pylint: disable=inconsistent-return-statements - self, - topic_hostname: str, - events: List[_models.EventGridEvent], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: list[~event_grid_publisher_client.models.EventGridEvent] - :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 publish_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: IO - :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 publish_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: Union[List[_models.EventGridEvent], IO], **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Is either a [EventGridEvent] - type or a IO type. Required. - :type events: list[~event_grid_publisher_client.models.EventGridEvent] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = 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" - _json = None - _content = None - if isinstance(events, (IO, bytes)): - _content = events - else: - _json = self._serialize.body(events, "[EventGridEvent]") - - request = build_event_grid_publisher_publish_events_request( - content_type=content_type, - api_version=self._config.api_version, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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( # type: ignore # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) - - @distributed_trace_async - async def publish_cloud_event_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: List[_models.CloudEvent], **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: list[~event_grid_publisher_client.models.CloudEvent] - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: str = kwargs.pop( - "content_type", - _headers.pop("Content-Type", "application/cloudevents-batch+json; charset=utf-8"), - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - _json = self._serialize.body(events, "[CloudEvent]") - - request = build_event_grid_publisher_publish_cloud_event_events_request( - content_type=content_type, - api_version=self._config.api_version, - json=_json, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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( # type: ignore # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) - - @overload - async def publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: List[JSON], *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: list[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 publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Required. - :type events: IO - :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 publish_custom_event_events( # pylint: disable=inconsistent-return-statements - self, topic_hostname: str, events: Union[List[JSON], IO], **kwargs: Any - ) -> None: - """Publishes a batch of events to an Azure Event Grid topic. - - :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net. - Required. - :type topic_hostname: str - :param events: An array of events to be published to Event Grid. Is either a [JSON] type or a - IO type. Required. - :type events: list[JSON] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = 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" - _json = None - _content = None - if isinstance(events, (IO, bytes)): - _content = events - else: - _json = self._serialize.body(events, "[object]") - - request = build_event_grid_publisher_publish_custom_event_events_request( - content_type=content_type, - api_version=self._config.api_version, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "topicHostname": self._serialize.url("topic_hostname", topic_hostname, "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( # type: ignore # pylint: disable=protected-access - request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_vendor.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_vendor.py deleted file mode 100644 index 00914b6f308b..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/aio/_vendor.py +++ /dev/null @@ -1,26 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import TYPE_CHECKING - -from ._configuration import EventGridPublisherClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import AsyncPipelineClient - - from .._serialization import Deserializer, Serializer - - -class EventGridPublisherClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: EventGridPublisherClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/__init__.py deleted file mode 100644 index 2d1ec017aeba..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/__init__.py +++ /dev/null @@ -1,26 +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 ._models import CloudEvent -from ._models import EventGridEvent -from ._models import SubscriptionDeletedEventData -from ._models import SubscriptionValidationEventData -from ._models import SubscriptionValidationResponse -from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "CloudEvent", - "EventGridEvent", - "SubscriptionDeletedEventData", - "SubscriptionValidationEventData", - "SubscriptionValidationResponse", -] -__all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_models.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_models.py deleted file mode 100644 index b4819fe41bbc..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_generated/models/_models.py +++ /dev/null @@ -1,301 +0,0 @@ -# coding=utf-8 -# pylint: disable=too-many-lines -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -import sys -from typing import Any, Dict, Optional - -from .. import _serialization - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - - -class CloudEvent(_serialization.Model): # pylint: disable=too-many-instance-attributes - """Properties of an event published to an Event Grid topic using the CloudEvent 1.0 Schema. - - All required parameters must be populated in order to send to Azure. - - :ivar additional_properties: Unmatched properties from the message are deserialized to this - collection. - :vartype additional_properties: dict[str, any] - :ivar id: An identifier for the event. The combination of id and source must be unique for each - distinct event. Required. - :vartype id: str - :ivar source: Identifies the context in which an event happened. The combination of id and - source must be unique for each distinct event. Required. - :vartype source: str - :ivar data: Event data specific to the event type. - :vartype data: JSON - :ivar data_base64: Event data specific to the event type, encoded as a base64 string. - :vartype data_base64: bytes - :ivar type: Type of event related to the originating occurrence. Required. - :vartype type: str - :ivar time: The time (in UTC) the event was generated, in RFC3339 format. - :vartype time: ~datetime.datetime - :ivar specversion: The version of the CloudEvents specification which the event uses. Required. - :vartype specversion: str - :ivar dataschema: Identifies the schema that data adheres to. - :vartype dataschema: str - :ivar datacontenttype: Content type of data value. - :vartype datacontenttype: str - :ivar subject: This describes the subject of the event in the context of the event producer - (identified by source). - :vartype subject: str - """ - - _validation = { - "id": {"required": True}, - "source": {"required": True}, - "type": {"required": True}, - "specversion": {"required": True}, - } - - _attribute_map = { - "additional_properties": {"key": "", "type": "{object}"}, - "id": {"key": "id", "type": "str"}, - "source": {"key": "source", "type": "str"}, - "data": {"key": "data", "type": "object"}, - "data_base64": {"key": "data_base64", "type": "bytearray"}, - "type": {"key": "type", "type": "str"}, - "time": {"key": "time", "type": "iso-8601"}, - "specversion": {"key": "specversion", "type": "str"}, - "dataschema": {"key": "dataschema", "type": "str"}, - "datacontenttype": {"key": "datacontenttype", "type": "str"}, - "subject": {"key": "subject", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - source: str, - type: str, - specversion: str, - additional_properties: Optional[Dict[str, Any]] = None, - data: Optional[JSON] = None, - data_base64: Optional[bytes] = None, - time: Optional[datetime.datetime] = None, - dataschema: Optional[str] = None, - datacontenttype: Optional[str] = None, - subject: 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 id: An identifier for the event. The combination of id and source must be unique for - each distinct event. Required. - :paramtype id: str - :keyword source: Identifies the context in which an event happened. The combination of id and - source must be unique for each distinct event. Required. - :paramtype source: str - :keyword data: Event data specific to the event type. - :paramtype data: JSON - :keyword data_base64: Event data specific to the event type, encoded as a base64 string. - :paramtype data_base64: bytes - :keyword type: Type of event related to the originating occurrence. Required. - :paramtype type: str - :keyword time: The time (in UTC) the event was generated, in RFC3339 format. - :paramtype time: ~datetime.datetime - :keyword specversion: The version of the CloudEvents specification which the event uses. - Required. - :paramtype specversion: str - :keyword dataschema: Identifies the schema that data adheres to. - :paramtype dataschema: str - :keyword datacontenttype: Content type of data value. - :paramtype datacontenttype: str - :keyword subject: This describes the subject of the event in the context of the event producer - (identified by source). - :paramtype subject: str - """ - super().__init__(**kwargs) - self.additional_properties = additional_properties - self.id = id - self.source = source - self.data = data - self.data_base64 = data_base64 - self.type = type - self.time = time - self.specversion = specversion - self.dataschema = dataschema - self.datacontenttype = datacontenttype - self.subject = subject - - -class EventGridEvent(_serialization.Model): - """Properties of an event published to an Event Grid topic using the EventGrid Schema. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: An unique identifier for the event. Required. - :vartype id: str - :ivar topic: The resource path of the event source. - :vartype topic: str - :ivar subject: A resource path relative to the topic path. Required. - :vartype subject: str - :ivar data: Event data specific to the event type. Required. - :vartype data: JSON - :ivar event_type: The type of the event that occurred. Required. - :vartype event_type: str - :ivar event_time: The time (in UTC) the event was generated. Required. - :vartype event_time: ~datetime.datetime - :ivar metadata_version: The schema version of the event metadata. - :vartype metadata_version: str - :ivar data_version: The schema version of the data object. Required. - :vartype data_version: str - """ - - _validation = { - "id": {"required": True}, - "subject": {"required": True}, - "data": {"required": True}, - "event_type": {"required": True}, - "event_time": {"required": True}, - "metadata_version": {"readonly": True}, - "data_version": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "topic": {"key": "topic", "type": "str"}, - "subject": {"key": "subject", "type": "str"}, - "data": {"key": "data", "type": "object"}, - "event_type": {"key": "eventType", "type": "str"}, - "event_time": {"key": "eventTime", "type": "iso-8601"}, - "metadata_version": {"key": "metadataVersion", "type": "str"}, - "data_version": {"key": "dataVersion", "type": "str"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - subject: str, - data: JSON, - event_type: str, - event_time: datetime.datetime, - data_version: str, - topic: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: An unique identifier for the event. Required. - :paramtype id: str - :keyword topic: The resource path of the event source. - :paramtype topic: str - :keyword subject: A resource path relative to the topic path. Required. - :paramtype subject: str - :keyword data: Event data specific to the event type. Required. - :paramtype data: JSON - :keyword event_type: The type of the event that occurred. Required. - :paramtype event_type: str - :keyword event_time: The time (in UTC) the event was generated. Required. - :paramtype event_time: ~datetime.datetime - :keyword data_version: The schema version of the data object. Required. - :paramtype data_version: str - """ - super().__init__(**kwargs) - self.id = id - self.topic = topic - self.subject = subject - self.data = data - self.event_type = event_type - self.event_time = event_time - self.metadata_version: Optional[str] = None - self.data_version = data_version - - -class SubscriptionDeletedEventData(_serialization.Model): - """Schema of the Data property of an EventGridEvent for a - Microsoft.EventGrid.SubscriptionDeletedEvent event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar event_subscription_id: The Azure resource ID of the deleted event subscription. - :vartype event_subscription_id: str - """ - - _validation = { - "event_subscription_id": {"readonly": True}, - } - - _attribute_map = { - "event_subscription_id": {"key": "eventSubscriptionId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.event_subscription_id = None - - -class SubscriptionValidationEventData(_serialization.Model): - """Schema of the Data property of an EventGridEvent for a - Microsoft.EventGrid.SubscriptionValidationEvent event. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar validation_code: The validation code sent by Azure Event Grid to validate an event - subscription. To complete the validation handshake, the subscriber must either respond with - this validation code as part of the validation response, or perform a GET request on the - validationUrl (available starting version 2018-05-01-preview). - :vartype validation_code: str - :ivar validation_url: The validation URL sent by Azure Event Grid (available starting version - 2018-05-01-preview). To complete the validation handshake, the subscriber must either respond - with the validationCode as part of the validation response, or perform a GET request on the - validationUrl (available starting version 2018-05-01-preview). - :vartype validation_url: str - """ - - _validation = { - "validation_code": {"readonly": True}, - "validation_url": {"readonly": True}, - } - - _attribute_map = { - "validation_code": {"key": "validationCode", "type": "str"}, - "validation_url": {"key": "validationUrl", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.validation_code = None - self.validation_url = None - - -class SubscriptionValidationResponse(_serialization.Model): - """To complete an event subscription validation handshake, a subscriber can use either the - validationCode or the validationUrl received in a SubscriptionValidationEvent. When the - validationCode is used, the SubscriptionValidationResponse can be used to build the response. - - :ivar validation_response: The validation response sent by the subscriber to Azure Event Grid - to complete the validation of an event subscription. - :vartype validation_response: str - """ - - _attribute_map = { - "validation_response": {"key": "validationResponse", "type": "str"}, - } - - def __init__(self, *, validation_response: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword validation_response: The validation response sent by the subscriber to Azure Event - Grid to complete the validation of an event subscription. - :paramtype validation_response: str - """ - super().__init__(**kwargs) - self.validation_response = validation_response diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py deleted file mode 100644 index 467466f6d9aa..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py +++ /dev/null @@ -1,187 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -from typing import TYPE_CHECKING, Any, Dict -import json -import hashlib -import hmac -import base64 - -from urllib.parse import quote - -from azure.core.pipeline.transport import HttpRequest -from azure.core.pipeline.policies import ( - AzureKeyCredentialPolicy, - BearerTokenCredentialPolicy, -) -from azure.core.credentials import AzureKeyCredential, AzureSasCredential -from ._generated._serialization import Serializer -from ._signature_credential_policy import EventGridSasCredentialPolicy -from . import _constants as constants - -from ._generated.models import ( - CloudEvent as InternalCloudEvent, -) - -if TYPE_CHECKING: - from datetime import datetime - - -def generate_sas( - endpoint: str, - shared_access_key: str, - expiration_date_utc: "datetime", - *, - api_version: str = constants.DEFAULT_API_VERSION, -) -> str: - """Helper method to generate shared access signature given hostname, key, and expiration date. - :param str endpoint: The topic endpoint to send the events to. - Similar to .-1.eventgrid.azure.net - :param str shared_access_key: The shared access key to be used for generating the token - :param datetime.datetime expiration_date_utc: The expiration datetime in UTC for the signature. - :keyword str api_version: The API Version to include in the signature. - If not provided, the default API version will be used. - :return: A shared access signature string. - :rtype: str - - - .. admonition:: Example: - - .. literalinclude:: ../samples/basic/sync_samples/sample_generate_sas.py - :start-after: [START generate_sas] - :end-before: [END generate_sas] - :language: python - :dedent: 0 - :caption: Generate a shared access signature. - - """ - full_endpoint = "{}?apiVersion={}".format(endpoint, api_version) - encoded_resource = quote(full_endpoint, safe=constants.SAFE_ENCODE) - encoded_expiration_utc = quote(str(expiration_date_utc), safe=constants.SAFE_ENCODE) - - unsigned_sas = "r={}&e={}".format(encoded_resource, encoded_expiration_utc) - signature = quote(_generate_hmac(shared_access_key, unsigned_sas), safe=constants.SAFE_ENCODE) - signed_sas = "{}&s={}".format(unsigned_sas, signature) - return signed_sas - - -def _generate_hmac(key, message): - decoded_key = base64.b64decode(key) - bytes_message = message.encode("ascii") - hmac_new = hmac.new(decoded_key, bytes_message, hashlib.sha256).digest() - - return base64.b64encode(hmac_new) - - -def _get_authentication_policy(credential, bearer_token_policy=BearerTokenCredentialPolicy): - if credential is None: - raise ValueError("Parameter 'self._credential' must not be None.") - if hasattr(credential, "get_token"): - return bearer_token_policy(credential, constants.DEFAULT_EVENTGRID_SCOPE) - if isinstance(credential, AzureKeyCredential): - return AzureKeyCredentialPolicy(credential=credential, name=constants.EVENTGRID_KEY_HEADER) - if isinstance(credential, AzureSasCredential): - return EventGridSasCredentialPolicy(credential=credential, name=constants.EVENTGRID_TOKEN_HEADER) - raise ValueError( - "The provided credential should be an instance of a TokenCredential, AzureSasCredential or AzureKeyCredential" - ) - - -def _is_cloud_event(event): - # type: (Any) -> bool - required = ("id", "source", "specversion", "type") - try: - return all((_ in event for _ in required)) and event["specversion"] == "1.0" - except TypeError: - return False - - -def _is_eventgrid_event_format(event): - # type: (Any) -> bool - required = ("subject", "eventType", "data", "dataVersion", "id", "eventTime") - try: - return all((prop in event for prop in required)) - except TypeError: - return False - - -def _eventgrid_data_typecheck(event): - try: - data = event.get("data") - except AttributeError: - data = event.data - - if isinstance(data, bytes): - raise TypeError( - "Data in EventGridEvent cannot be bytes. Please refer to" - "https://docs.microsoft.com/en-us/azure/event-grid/event-schema" - ) - - -def _cloud_event_to_generated(cloud_event, **kwargs): - if isinstance(cloud_event.data, bytes): - data_base64 = cloud_event.data - data = None - else: - data = cloud_event.data - data_base64 = None - return InternalCloudEvent( - id=cloud_event.id, - source=cloud_event.source, - type=cloud_event.type, - specversion=cloud_event.specversion, - data=data, - data_base64=data_base64, - time=cloud_event.time, - dataschema=cloud_event.dataschema, - datacontenttype=cloud_event.datacontenttype, - subject=cloud_event.subject, - additional_properties=cloud_event.extensions, - **kwargs, - ) - - -def _from_cncf_events(event): # pylint: disable=inconsistent-return-statements - """This takes in a CNCF cloudevent and returns a dictionary. - If cloud events library is not installed, the event is returned back. - - :param event: The event to be serialized - :type event: cloudevents.http.CloudEvent - :return: The serialized event - :rtype: any - """ - try: - from cloudevents.http import to_json - - return json.loads(to_json(event)) - except (AttributeError, ImportError): - # means this is not a CNCF event - return event - except Exception as err: # pylint: disable=broad-except - msg = """Failed to serialize the event. Please ensure your - CloudEvents is correctly formatted (https://pypi.org/project/cloudevents/)""" - raise ValueError(msg) from err - - -def _build_request(endpoint, content_type, events, *, channel_name=None, api_version=constants.DEFAULT_API_VERSION): - serialize = Serializer() - header_parameters: Dict[str, Any] = {} - header_parameters["Content-Type"] = serialize.header("content_type", content_type, "str") - - if channel_name: - header_parameters["aeg-channel-name"] = channel_name - - query_parameters: Dict[str, Any] = {} - query_parameters["api-version"] = serialize.query("api_version", api_version, "str") - - body = serialize.body(events, "[object]") - if body is None: - data = None - else: - data = json.dumps(body) - header_parameters["Content-Length"] = str(len(data)) - - request = HttpRequest(method="POST", url=endpoint, headers=header_parameters, data=data) - request.format_parameters(query_parameters) - return request diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_messaging_shared.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_messaging_shared.py deleted file mode 100644 index a08af498bff0..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_messaging_shared.py +++ /dev/null @@ -1,46 +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. -# -------------------------------------------------------------------------- - -# ========================================================================== -# This file contains duplicate code that is shared with azure-eventgrid. -# Both the files should always be identical. -# ========================================================================== - -from typing import Any -import json - - -def _get_json_content(obj: Any) -> Any: # pylint: disable=inconsistent-return-statements - """Event mixin to have methods that are common to different Event types - like CloudEvent, EventGridEvent etc. - - :param obj: The object to get the JSON content from. - :type obj: any - :return: The JSON content from the object. - :rtype: any - :raises: ValueError if the JSON content cannot be loaded from the object. - """ - msg = "Failed to load JSON content from the object." - try: - # storage queue - return json.loads(obj.content) - except ValueError as err: - raise ValueError(msg) from err - except AttributeError: - # eventhubs - try: - return json.loads(next(obj.body))[0] - except KeyError: - # servicebus - return json.loads(next(obj.body)) - except ValueError as err: - raise ValueError(msg) from err - except: # pylint: disable=bare-except - try: - return json.loads(obj) - except ValueError as err: - raise ValueError(msg) from err diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_models.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_models.py deleted file mode 100644 index 6586e5e22793..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_models.py +++ /dev/null @@ -1,112 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- -# pylint:disable=protected-access -from typing import Any, cast -import datetime as dt -import uuid -from ._messaging_shared import _get_json_content -from ._generated.models import ( - EventGridEvent as InternalEventGridEvent, -) - - -class EventGridEvent(InternalEventGridEvent): - """Properties of an event published to an Event Grid topic using the EventGrid Schema. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :param subject: Required. A resource path relative to the topic path. - :type subject: str - :param event_type: Required. The type of the event that occurred. - :type event_type: str - :param data: Required. Event data specific to the event type. - :type data: object - :param data_version: Required. The schema version of the data object. - If not provided, will be stamped with an empty value. - :type data_version: str - :keyword topic: The resource path of the event source. If not provided, Event Grid will - stamp onto the event. This is required when sending event(s) to a domain. - :paramtype topic: Optional[str] - :keyword metadata_version: The schema version of the event metadata. If provided, - must match Event Grid Schema exactly. If not provided, EventGrid will stamp onto event. - :paramtype metadata_version: Optional[str] - :keyword id: An identifier for the event. In not provided, a random UUID will be generated and used. - :paramtype id: Optional[str] - :keyword event_time: The time (in UTC) of the event. If not provided, - it will be the time (in UTC) the event was generated. - :paramtype event_time: Optional[~datetime.datetime] - :ivar subject: A resource path relative to the topic path. - :vartype subject: str - :ivar event_type: The type of the event that occurred. - :vartype event_type: str - :ivar data: Event data specific to the event type. - :vartype data: object - :ivar data_version: The schema version of the data object. - If not provided, will be stamped with an empty value. - :vartype data_version: str - :ivar topic: The resource path of the event source. If not provided, Event Grid will stamp onto the event. - :vartype topic: str - :ivar metadata_version: The schema version of the event metadata. If provided, must match Event Grid Schema exactly. - If not provided, EventGrid will stamp onto event. - :vartype metadata_version: str - :ivar id: An identifier for the event. In not provided, a random UUID will be generated and used. - :vartype id: str - :ivar event_time: The time (in UTC) of the event. If not provided, - it will be the time (in UTC) the event was generated. - :vartype event_time: ~datetime.datetime - """ - - _validation = { - "id": {"required": True}, - "subject": {"required": True}, - "data": {"required": True}, - "event_type": {"required": True}, - "event_time": {"required": True}, - "metadata_version": {"readonly": True}, - "data_version": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "topic": {"key": "topic", "type": "str"}, - "subject": {"key": "subject", "type": "str"}, - "data": {"key": "data", "type": "object"}, - "event_type": {"key": "eventType", "type": "str"}, - "event_time": {"key": "eventTime", "type": "iso-8601"}, - "metadata_version": {"key": "metadataVersion", "type": "str"}, - "data_version": {"key": "dataVersion", "type": "str"}, - } - - def __init__(self, subject: str, event_type: str, data: Any, data_version: str, **kwargs: Any) -> None: - kwargs.setdefault("id", uuid.uuid4()) - kwargs.setdefault("subject", subject) - kwargs.setdefault("event_type", event_type) - kwargs.setdefault("event_time", dt.datetime.now(dt.timezone.utc).isoformat()) - kwargs.setdefault("data", data) - kwargs.setdefault("data_version", data_version) - - super(EventGridEvent, self).__init__(**kwargs) - - def __repr__(self) -> str: - return "EventGridEvent(subject={}, event_type={}, id={}, event_time={})".format( - self.subject, self.event_type, self.id, self.event_time - )[:1024] - - @classmethod - def from_json(cls, event: Any) -> "EventGridEvent": - """ - Returns the deserialized EventGridEvent object when a json payload is provided. - :param event: The json string that should be converted into a EventGridEvent. This can also be - a storage QueueMessage, eventhub's EventData or ServiceBusMessage - :type event: object - :rtype: EventGridEvent - :return: An EventGridEvent object. - :raises ValueError: If the provided JSON is invalid. - - """ - dict_event = _get_json_content(event) - return cast(EventGridEvent, EventGridEvent.from_dict(dict_event)) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_policies.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_policies.py deleted file mode 100644 index d4f2dcfd5638..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_policies.py +++ /dev/null @@ -1,48 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import json -from typing import TYPE_CHECKING -import logging -from azure.core.pipeline.policies import SansIOHTTPPolicy - -_LOGGER = logging.getLogger(__name__) - -if TYPE_CHECKING: - from azure.core.pipeline import PipelineRequest - - -class CloudEventDistributedTracingPolicy(SansIOHTTPPolicy): - """CloudEventDistributedTracingPolicy is a policy which adds distributed tracing information - to a batch of cloud events. It does so by copying the `traceparent` and `tracestate` properties - from the HTTP request into the individual events as extension properties. - This will only happen in the case where an event does not have a `traceparent` defined already. This - allows events to explicitly set a traceparent and tracestate which would be respected during "multi-hop - transmission". - See https://github.com/cloudevents/spec/blob/master/extensions/distributed-tracing.md - for more information on distributed tracing and cloud events. - """ - - _CONTENT_TYPE = "application/cloudevents-batch+json; charset=utf-8" - - def on_request(self, request): - # type: (PipelineRequest) -> None - try: - traceparent = request.http_request.headers["traceparent"] - tracestate = request.http_request.headers["tracestate"] - except KeyError: - return - - if ( - request.http_request.headers["content-type"] == CloudEventDistributedTracingPolicy._CONTENT_TYPE - and traceparent is not None - ): - body = json.loads(request.http_request.body) - for item in body: - if "traceparent" not in item and "tracestate" not in item: - item["traceparent"] = traceparent - item["tracestate"] = tracestate - - request.http_request.body = json.dumps(body) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py deleted file mode 100644 index f329e05ddded..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py +++ /dev/null @@ -1,250 +0,0 @@ -# -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from typing import TYPE_CHECKING, cast, Dict, List, Any, Union, Optional - -from azure.core.tracing.decorator import distributed_trace -from azure.core.pipeline.policies import ( - RequestIdPolicy, - HeadersPolicy, - RedirectPolicy, - RetryPolicy, - ContentDecodePolicy, - CustomHookPolicy, - NetworkTraceLoggingPolicy, - ProxyPolicy, - DistributedTracingPolicy, - HttpLoggingPolicy, - UserAgentPolicy, -) -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceNotFoundError, - ResourceExistsError, - map_error, -) -from azure.core.messaging import CloudEvent - -from ._models import EventGridEvent -from ._helpers import ( - _get_authentication_policy, - _is_cloud_event, - _is_eventgrid_event_format, - _eventgrid_data_typecheck, - _build_request, - _cloud_event_to_generated, - _from_cncf_events, -) -from ._generated import ( - EventGridPublisherClient as EventGridPublisherClientImpl, -) -from ._policies import CloudEventDistributedTracingPolicy -from ._constants import DEFAULT_API_VERSION -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import ( - AzureKeyCredential, - AzureSasCredential, - TokenCredential, - ) - - from cloudevents.http.event import CloudEvent as CNCFCloudEvent - -SendType = Union[ - CloudEvent, - EventGridEvent, - Dict, - "CNCFCloudEvent", - List[CloudEvent], - List[EventGridEvent], - List[Dict], - List["CNCFCloudEvent"], -] - -ListEventType = Union[List[CloudEvent], List[EventGridEvent], List[Dict]] - - -class EventGridPublisherClient(object): # pylint: disable=client-accepts-api-version-keyword - """EventGridPublisherClient publishes events to an EventGrid topic or domain. - It can be used to publish either an EventGridEvent, a CloudEvent or a Custom Schema. - - :param str endpoint: The topic endpoint to send the events to. - :param credential: The credential object used for authentication which - implements SAS key authentication or SAS token authentication or a TokenCredential. - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or - ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Will default to the most recent Api Version. Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :rtype: None - - .. admonition:: Example: - - .. literalinclude:: ../samples/basic/sync_samples/sample_authentication.py - :start-after: [START client_auth_with_key_cred] - :end-before: [END client_auth_with_key_cred] - :language: python - :dedent: 0 - :caption: Creating the EventGridPublisherClient with an endpoint and AzureKeyCredential. - - .. literalinclude:: ../samples/basic/sync_samples/sample_authentication.py - :start-after: [START client_auth_with_sas_cred] - :end-before: [END client_auth_with_sas_cred] - :language: python - :dedent: 0 - :caption: Creating the EventGridPublisherClient with an endpoint and AzureSasCredential. - """ - - def __init__( - self, - endpoint: str, - credential: Union["AzureKeyCredential", "AzureSasCredential", "TokenCredential"], - *, - api_version: Optional[str] = None, - **kwargs: Any - ) -> None: - self._endpoint = endpoint - self._client = EventGridPublisherClientImpl( - policies=EventGridPublisherClient._policies(credential, **kwargs), **kwargs - ) - self._api_version = api_version if api_version is not None else DEFAULT_API_VERSION - - @staticmethod - def _policies(credential, **kwargs): - # type: (Union[AzureKeyCredential, AzureSasCredential, TokenCredential], Any) -> List[Any] - auth_policy = _get_authentication_policy(credential) - sdk_moniker = "eventgrid/{}".format(VERSION) - policies = [ - RequestIdPolicy(**kwargs), - HeadersPolicy(**kwargs), - UserAgentPolicy(sdk_moniker=sdk_moniker, **kwargs), - ProxyPolicy(**kwargs), - ContentDecodePolicy(**kwargs), - RedirectPolicy(**kwargs), - RetryPolicy(**kwargs), - auth_policy, - CustomHookPolicy(**kwargs), - NetworkTraceLoggingPolicy(**kwargs), - DistributedTracingPolicy(**kwargs), - CloudEventDistributedTracingPolicy(), - HttpLoggingPolicy(**kwargs), - ] - return policies - - @distributed_trace - def send(self, events: SendType, *, channel_name: Optional[str] = None, **kwargs: Any) -> None: - """Sends events to a topic or a domain specified during the client initialization. - - A single instance or a list of dictionaries, CloudEvents or EventGridEvents are accepted. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_publish_eg_events_to_a_topic.py - :start-after: [START publish_eg_event_to_topic] - :end-before: [END publish_eg_event_to_topic] - :language: python - :dedent: 0 - :caption: Publishing an EventGridEvent. - - .. literalinclude:: ../samples/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py - :start-after: [START publish_cloud_event_to_topic] - :end-before: [END publish_cloud_event_to_topic] - :language: python - :dedent: 0 - :caption: Publishing a CloudEvent. - - Dict representation of respective serialized models is accepted as CloudEvent(s) or - EventGridEvent(s) apart from the strongly typed objects. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_publish_eg_event_using_dict.py - :start-after: [START publish_eg_event_dict] - :end-before: [END publish_eg_event_dict] - :language: python - :dedent: 4 - :caption: Publishing a list of EventGridEvents using a dict-like representation. - - .. literalinclude:: ../samples/sync_samples/sample_publish_cloud_event_using_dict.py - :start-after: [START publish_cloud_event_dict] - :end-before: [END publish_cloud_event_dict] - :language: python - :dedent: 0 - :caption: Publishing a CloudEvent using a dict-like representation. - - When publishing a Custom Schema Event(s), dict-like representation is accepted. - Either a single dictionary or a list of dictionaries can be passed. - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_publish_custom_schema_to_a_topic.py - :start-after: [START publish_custom_schema] - :end-before: [END publish_custom_schema] - :language: python - :dedent: 4 - :caption: Publishing a Custom Schema event. - - **WARNING**: When sending a list of multiple events at one time, iterating over and sending each event - will not result in optimal performance. For best performance, it is highly recommended to send - a list of events. - - :param events: A single instance or a list of dictionaries/CloudEvent/EventGridEvent to be sent. - :type events: ~azure.core.messaging.CloudEvent or ~azure.eventgrid.EventGridEvent or dict or - List[~azure.core.messaging.CloudEvent] or List[~azure.eventgrid.EventGridEvent] or List[dict] - :keyword str content_type: The type of content to be used to send the events. - Has default value "application/json; charset=utf-8" for EventGridEvents, - with "cloudevents-batch+json" for CloudEvents - :keyword channel_name: Optional. Used to specify the name of event channel when publishing to partner. - :paramtype channel_name: str or None - namespaces with partner topic. For more details, visit - https://docs.microsoft.com/azure/event-grid/partner-events-overview - :rtype: None - """ - if not isinstance(events, list): - events = cast(ListEventType, [events]) - content_type = kwargs.pop("content_type", "application/json; charset=utf-8") - if isinstance(events[0], CloudEvent) or _is_cloud_event(events[0]): - try: - events = [_cloud_event_to_generated(e, **kwargs) for e in events] # pylint: disable=protected-access - except AttributeError: - ## this is either a dictionary or a CNCF cloud event - events = [_from_cncf_events(e) for e in events] - content_type = "application/cloudevents-batch+json; charset=utf-8" - elif isinstance(events[0], EventGridEvent) or _is_eventgrid_event_format(events[0]): - for event in events: - _eventgrid_data_typecheck(event) - response = self._client.send_request( # pylint: disable=protected-access - _build_request( - self._endpoint, content_type, events, channel_name=channel_name, api_version=self._api_version - ), - **kwargs - ) - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - } - if response.status_code != 200: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - def close(self): - # type: () -> None - """Close the :class:`~azure.eventgrid.EventGridPublisherClient` session.""" - return self._client.close() - - def __enter__(self): - # type: () -> EventGridPublisherClient - self._client.__enter__() # pylint:disable=no-member - return self - - def __exit__(self, *args): - # type: (*Any) -> None - self._client.__exit__(*args) # pylint:disable=no-member diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_signature_credential_policy.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_signature_credential_policy.py deleted file mode 100644 index ca6004fed451..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_signature_credential_policy.py +++ /dev/null @@ -1,35 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See LICENSE.txt in the project root for -# license information. -# ------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.pipeline.policies import SansIOHTTPPolicy - -if TYPE_CHECKING: - from azure.core.credentials import AzureSasCredential - - -class EventGridSasCredentialPolicy(SansIOHTTPPolicy): - """Adds a token header for the provided credential. - :param credential: The credential used to authenticate requests. - :type credential: ~azure.core.credentials.AzureSasCredential - :param str name: The name of the token header used for the credential. - :raises: ValueError or TypeError - """ - - def __init__(self, credential, name, **kwargs): # pylint: disable=unused-argument - # type: (AzureSasCredential, str, Any) -> None - super(EventGridSasCredentialPolicy, self).__init__() - self._credential = credential - if not name: - raise ValueError("name can not be None or empty") - if not isinstance(name, str): - raise TypeError("name must be a string.") - self._name = name - - def on_request(self, request): - # Request must contain one of the following authorization signature: aeg-sas-token, aeg-sas-key - request.http_request.headers[self._name] = self._credential.signature diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_version.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_version.py deleted file mode 100644 index c9812c54f54c..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_version.py +++ /dev/null @@ -1,12 +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. -# -------------------------------------------------------------------------- - -VERSION = "4.10.0" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/__init__.py deleted file mode 100644 index 0d2dce7aaea2..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from ._publisher_client_async import EventGridPublisherClient - -__all__ = ["EventGridPublisherClient"] diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py deleted file mode 100644 index ad718665ac01..000000000000 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py +++ /dev/null @@ -1,242 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Union, List, Dict, TYPE_CHECKING, cast, Optional -from azure.core.credentials import AzureKeyCredential, AzureSasCredential -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.messaging import CloudEvent -from azure.core.pipeline.policies import ( - RequestIdPolicy, - HeadersPolicy, - AsyncRedirectPolicy, - AsyncRetryPolicy, - ContentDecodePolicy, - CustomHookPolicy, - NetworkTraceLoggingPolicy, - ProxyPolicy, - DistributedTracingPolicy, - HttpLoggingPolicy, - UserAgentPolicy, - AsyncBearerTokenCredentialPolicy, -) -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceNotFoundError, - ResourceExistsError, - map_error, -) -from .._policies import CloudEventDistributedTracingPolicy -from .._models import EventGridEvent -from .._helpers import ( - _is_cloud_event, - _is_eventgrid_event_format, - _eventgrid_data_typecheck, - _build_request, - _cloud_event_to_generated, - _get_authentication_policy, - _from_cncf_events, -) -from .._constants import DEFAULT_API_VERSION -from .._generated.aio import EventGridPublisherClient as EventGridPublisherClientAsync -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core.credentials_async import AsyncTokenCredential - - from cloudevents.http.event import CloudEvent as CNCFCloudEvent - -SendType = Union[ - CloudEvent, - EventGridEvent, - Dict, - "CNCFCloudEvent", - List[CloudEvent], - List[EventGridEvent], - List[Dict], - List["CNCFCloudEvent"], -] - -ListEventType = Union[List[CloudEvent], List[EventGridEvent], List[Dict]] - - -class EventGridPublisherClient: # pylint: disable=client-accepts-api-version-keyword - """Asynchronous EventGridPublisherClient publishes events to an EventGrid topic or domain. - It can be used to publish either an EventGridEvent, a CloudEvent or a Custom Schema. - - :param str endpoint: The topic endpoint to send the events to. - :param credential: The credential object used for authentication which implements - SAS key authentication or SAS token authentication or an AsyncTokenCredential. - :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or - ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Will default to the most recent Api Version. Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :rtype: None - - .. admonition:: Example: - - .. literalinclude:: ../samples/basic/async_samples/sample_authentication_async.py - :start-after: [START client_auth_with_key_cred_async] - :end-before: [END client_auth_with_key_cred_async] - :language: python - :dedent: 0 - :caption: Creating the EventGridPublisherClient with an endpoint and AzureKeyCredential. - - .. literalinclude:: ../samples/basic/async_samples/sample_authentication_async.py - :start-after: [START client_auth_with_sas_cred_async] - :end-before: [END client_auth_with_sas_cred_async] - :language: python - :dedent: 0 - :caption: Creating the EventGridPublisherClient with an endpoint and AzureSasCredential. - """ - - def __init__( - self, - endpoint: str, - credential: Union["AsyncTokenCredential", AzureKeyCredential, AzureSasCredential], - *, - api_version: Optional[str] = None, - **kwargs: Any - ) -> None: - self._client = EventGridPublisherClientAsync( - policies=EventGridPublisherClient._policies(credential, **kwargs), **kwargs - ) - self._endpoint = endpoint - self._api_version = api_version if api_version is not None else DEFAULT_API_VERSION - - @staticmethod - def _policies( - credential: Union[AzureKeyCredential, AzureSasCredential, "AsyncTokenCredential"], **kwargs: Any - ) -> List[Any]: - auth_policy = _get_authentication_policy(credential, AsyncBearerTokenCredentialPolicy) - sdk_moniker = "eventgridpublisherclient/{}".format(VERSION) - policies = [ - RequestIdPolicy(**kwargs), - HeadersPolicy(**kwargs), - UserAgentPolicy(sdk_moniker=sdk_moniker, **kwargs), - ProxyPolicy(**kwargs), - ContentDecodePolicy(**kwargs), - AsyncRedirectPolicy(**kwargs), - AsyncRetryPolicy(**kwargs), - auth_policy, - CustomHookPolicy(**kwargs), - NetworkTraceLoggingPolicy(**kwargs), - DistributedTracingPolicy(**kwargs), - CloudEventDistributedTracingPolicy(), - HttpLoggingPolicy(**kwargs), - ] - return policies - - @distributed_trace_async - async def send(self, events: SendType, *, channel_name: Optional[str] = None, **kwargs: Any) -> None: - """Sends events to a topic or a domain specified during the client initialization. - - A single instance or a list of dictionaries, CloudEvents or EventGridEvents are accepted. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_publish_eg_events_to_a_topic_async.py - :start-after: [START publish_eg_event_to_topic_async] - :end-before: [END publish_eg_event_to_topic_async] - :language: python - :dedent: 0 - :caption: Publishing an EventGridEvent. - - .. literalinclude:: ../samples/async_samples/sample_publish_events_using_cloud_events_1.0_schema_async.py - :start-after: [START publish_cloud_event_to_topic_async] - :end-before: [END publish_cloud_event_to_topic_async] - :language: python - :dedent: 0 - :caption: Publishing a CloudEvent. - - Dict representation of respective serialized models is accepted as CloudEvent(s) or - EventGridEvent(s) apart from the strongly typed objects. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_publish_eg_event_using_dict_async.py - :start-after: [START publish_eg_event_dict_async] - :end-before: [END publish_eg_event_dict_async] - :language: python - :dedent: 4 - :caption: Publishing a list of EventGridEvents using a dict-like representation. - - .. literalinclude:: ../samples/async_samples/sample_publish_cloud_event_using_dict_async.py - :start-after: [START publish_cloud_event_dict_async] - :end-before: [END publish_cloud_event_dict_async] - :language: python - :dedent: 4 - :caption: Publishing a CloudEvent using a dict-like representation. - - When publishing a Custom Schema Event(s), dict-like representation is accepted. - Either a single dictionary or a list of dictionaries can be passed. - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_publish_custom_schema_to_a_topic_async.py - :start-after: [START publish_custom_schema_async] - :end-before: [END publish_custom_schema_async] - :language: python - :dedent: 4 - :caption: Publishing a Custom Schema event. - - **WARNING**: When sending a list of multiple events at one time, iterating over and sending each event - will not result in optimal performance. For best performance, it is highly recommended to send - a list of events. - - :param events: A single instance or a list of dictionaries/CloudEvent/EventGridEvent to be sent. - :type events: ~azure.core.messaging.CloudEvent or ~azure.eventgrid.EventGridEvent or dict or - List[~azure.core.messaging.CloudEvent] or List[~azure.eventgrid.EventGridEvent] or List[dict] - :keyword str content_type: The type of content to be used to send the events. - Has default value "application/json; charset=utf-8" for EventGridEvents, - with "cloudevents-batch+json" for CloudEvents - :keyword channel_name: Optional. Used to specify the name of event channel when publishing to partner - :paramtype channel_name: str or None - namespaces with partner topic. For more details, visit - https://docs.microsoft.com/azure/event-grid/partner-events-overview - :rtype: None - """ - if not isinstance(events, list): - events = cast(ListEventType, [events]) - content_type = kwargs.pop("content_type", "application/json; charset=utf-8") - if isinstance(events[0], CloudEvent) or _is_cloud_event(events[0]): - try: - events = [_cloud_event_to_generated(e, **kwargs) for e in events] # pylint: disable=protected-access - except AttributeError: - ## this is either a dictionary or a CNCF cloud event - events = [_from_cncf_events(e) for e in events] - content_type = "application/cloudevents-batch+json; charset=utf-8" - elif isinstance(events[0], EventGridEvent) or _is_eventgrid_event_format(events[0]): - for event in events: - _eventgrid_data_typecheck(event) - response = await self._client.send_request( # pylint: disable=protected-access - _build_request( - self._endpoint, content_type, events, channel_name=channel_name, api_version=self._api_version - ), - **kwargs - ) - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - } - if response.status_code != 200: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - async def __aenter__(self) -> "EventGridPublisherClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *args: "Any") -> None: - await self._client.__aexit__(*args) - - async def close(self) -> None: - """Close the :class:`~azure.eventgrid.aio.EventGridPublisherClient` session.""" - await self._client.__aexit__() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py index 5cf70733404d..43fd8c7e9b1b 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py @@ -883,5 +883,6 @@ def rest_discriminator( *, name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[typing.List[str]] = None, ) -> typing.Any: - return _RestField(name=name, type=type, is_discriminator=True) + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py index c716622cb722..9d2dc639460a 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py @@ -6,8 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import EventGridPublisherClientOperationsMixin -from ._patch import EventGridConsumerClientOperationsMixin +from ._operations import EventGridPublisherClientOperationsMixin +from ._operations import EventGridConsumerClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py index b2094313f8e6..4905e1a011d6 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py @@ -17,6 +17,8 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -267,7 +269,6 @@ class EventGridPublisherClientOperationsMixin(EventGridPublisherClientMixinABC): def _send( # pylint: disable=protected-access self, topic_name: str, event: _models._models.CloudEvent, **kwargs: Any ) -> _models._models.PublishResult: - # pylint: disable=line-too-long """Publish a single Cloud Event to a namespace topic. :param topic_name: Topic Name. Required. @@ -283,23 +284,16 @@ def _send( # pylint: disable=protected-access # JSON input template you can fill out and use as your body input. event = { - "id": "str", # An identifier for the event. The combination of id and source - must be unique for each distinct event. Required. - "source": "str", # Identifies the context in which an event happened. The - combination of id and source must be unique for each distinct event. Required. - "specversion": "str", # The version of the CloudEvents specification which - the event uses. Required. - "type": "str", # Type of event related to the originating occurrence. - Required. - "data": {}, # Optional. Event data specific to the event type. - "data_base64": bytes("bytes", encoding="utf-8"), # Optional. Event data - specific to the event type, encoded as a base64 string. - "datacontenttype": "str", # Optional. Content type of data value. - "dataschema": "str", # Optional. Identifies the schema that data adheres to. - "subject": "str", # Optional. This describes the subject of the event in the - context of the event producer (identified by source). - "time": "2020-02-20 00:00:00" # Optional. The time (in UTC) the event was - generated, in RFC3339 format. + "id": "str", + "source": "str", + "specversion": "str", + "type": "str", + "data": {}, + "data_base64": bytes("bytes", encoding="utf-8"), + "datacontenttype": "str", + "dataschema": "str", + "subject": "str", + "time": "2020-02-20 00:00:00" } """ error_map: MutableMapping[int, Type[HttpResponseError]] = { @@ -342,7 +336,10 @@ def _send( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -362,7 +359,6 @@ def _send( # pylint: disable=protected-access def _send_events( # pylint: disable=protected-access self, topic_name: str, events: List[_models._models.CloudEvent], **kwargs: Any ) -> _models._models.PublishResult: - # pylint: disable=line-too-long """Publish a batch of Cloud Events to a namespace topic. :param topic_name: Topic Name. Required. @@ -379,25 +375,16 @@ def _send_events( # pylint: disable=protected-access # JSON input template you can fill out and use as your body input. events = [ { - "id": "str", # An identifier for the event. The combination of id - and source must be unique for each distinct event. Required. - "source": "str", # Identifies the context in which an event - happened. The combination of id and source must be unique for each distinct - event. Required. - "specversion": "str", # The version of the CloudEvents specification - which the event uses. Required. - "type": "str", # Type of event related to the originating - occurrence. Required. - "data": {}, # Optional. Event data specific to the event type. - "data_base64": bytes("bytes", encoding="utf-8"), # Optional. Event - data specific to the event type, encoded as a base64 string. - "datacontenttype": "str", # Optional. Content type of data value. - "dataschema": "str", # Optional. Identifies the schema that data - adheres to. - "subject": "str", # Optional. This describes the subject of the - event in the context of the event producer (identified by source). - "time": "2020-02-20 00:00:00" # Optional. The time (in UTC) the - event was generated, in RFC3339 format. + "id": "str", + "source": "str", + "specversion": "str", + "type": "str", + "data": {}, + "data_base64": bytes("bytes", encoding="utf-8"), + "datacontenttype": "str", + "dataschema": "str", + "subject": "str", + "time": "2020-02-20 00:00:00" } ] """ @@ -441,7 +428,10 @@ def _send_events( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -470,7 +460,6 @@ def _receive( # pylint: disable=protected-access max_wait_time: Optional[int] = None, **kwargs: Any ) -> _models._models.ReceiveResult: - # pylint: disable=line-too-long """Receive a batch of Cloud Events from a subscription. :param topic_name: Topic Name. Required. @@ -498,36 +487,20 @@ def _receive( # pylint: disable=protected-access "value": [ { "brokerProperties": { - "deliveryCount": 0, # The attempt count for - delivering the event. Required. - "lockToken": "str" # The token of the lock on the - event. Required. + "deliveryCount": 0, + "lockToken": "str" }, "event": { - "id": "str", # An identifier for the event. The - combination of id and source must be unique for each distinct event. - Required. - "source": "str", # Identifies the context in which - an event happened. The combination of id and source must be unique - for each distinct event. Required. - "specversion": "str", # The version of the - CloudEvents specification which the event uses. Required. - "type": "str", # Type of event related to the - originating occurrence. Required. - "data": {}, # Optional. Event data specific to the - event type. - "data_base64": bytes("bytes", encoding="utf-8"), # - Optional. Event data specific to the event type, encoded as a base64 - string. - "datacontenttype": "str", # Optional. Content type - of data value. - "dataschema": "str", # Optional. Identifies the - schema that data adheres to. - "subject": "str", # Optional. This describes the - subject of the event in the context of the event producer (identified - by source). - "time": "2020-02-20 00:00:00" # Optional. The time - (in UTC) the event was generated, in RFC3339 format. + "id": "str", + "source": "str", + "specversion": "str", + "type": "str", + "data": {}, + "data_base64": bytes("bytes", encoding="utf-8"), + "datacontenttype": "str", + "dataschema": "str", + "subject": "str", + "time": "2020-02-20 00:00:00" } } ] @@ -569,7 +542,10 @@ def _receive( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -649,7 +625,7 @@ def _acknowledge( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -658,27 +634,22 @@ def _acknowledge( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. + "str" ] } """ @@ -731,7 +702,10 @@ def _acknowledge( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -746,9 +720,6 @@ def _acknowledge( return deserialized # type: ignore @overload - @api_version_validation( - params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, - ) def _release( self, topic_name: str, @@ -760,9 +731,6 @@ def _release( **kwargs: Any ) -> _models.ReleaseResult: ... @overload - @api_version_validation( - params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, - ) def _release( self, topic_name: str, @@ -774,9 +742,6 @@ def _release( **kwargs: Any ) -> _models.ReleaseResult: ... @overload - @api_version_validation( - params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, - ) def _release( self, topic_name: str, @@ -827,7 +792,7 @@ def _release( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -836,27 +801,22 @@ def _release( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. + "str" ] } """ @@ -910,7 +870,10 @@ def _release( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -987,7 +950,7 @@ def _reject( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -996,27 +959,22 @@ def _reject( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. + "str" ] } """ @@ -1069,7 +1027,10 @@ def _reject( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -1084,12 +1045,6 @@ def _reject( return deserialized # type: ignore @overload - @api_version_validation( - method_added_on="2023-10-01-preview", - params_added_on={ - "2023-10-01-preview": ["api_version", "topic_name", "event_subscription_name", "content_type", "accept"] - }, - ) def _renew_locks( self, topic_name: str, @@ -1100,12 +1055,6 @@ def _renew_locks( **kwargs: Any ) -> _models.RenewLocksResult: ... @overload - @api_version_validation( - method_added_on="2023-10-01-preview", - params_added_on={ - "2023-10-01-preview": ["api_version", "topic_name", "event_subscription_name", "content_type", "accept"] - }, - ) def _renew_locks( self, topic_name: str, @@ -1116,12 +1065,6 @@ def _renew_locks( **kwargs: Any ) -> _models.RenewLocksResult: ... @overload - @api_version_validation( - method_added_on="2023-10-01-preview", - params_added_on={ - "2023-10-01-preview": ["api_version", "topic_name", "event_subscription_name", "content_type", "accept"] - }, - ) def _renew_locks( self, topic_name: str, @@ -1171,7 +1114,7 @@ def _renew_locks( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -1180,27 +1123,22 @@ def _renew_locks( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. + "str" ] } """ @@ -1253,7 +1191,10 @@ def _renew_locks( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py index f0c6180722c8..8139854b97bb 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py @@ -144,6 +144,8 @@ def _json_attemp(data): # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py index 9462cc312640..c615ce560cb1 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "4.20.1" +VERSION = "4.20.0" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py index bcf16d1a1ec6..ac8497327815 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py @@ -6,8 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import EventGridPublisherClient -from ._patch import EventGridConsumerClient +from ._client import EventGridPublisherClient +from ._client import EventGridConsumerClient try: from ._patch import __all__ as _patch_all diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py index 07db6072d782..934f82051ec4 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py @@ -8,6 +8,7 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING, Union +from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.credentials import AzureKeyCredential @@ -99,7 +100,7 @@ def send_request( async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "EventGridPublisherClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self @@ -183,7 +184,7 @@ def send_request( async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "EventGridConsumerClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py index c716622cb722..9d2dc639460a 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py @@ -6,8 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import EventGridPublisherClientOperationsMixin -from ._patch import EventGridConsumerClientOperationsMixin +from ._operations import EventGridPublisherClientOperationsMixin +from ._operations import EventGridConsumerClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py index e10006e75b52..cedf1e505abe 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py @@ -17,6 +17,8 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -54,7 +56,6 @@ class EventGridPublisherClientOperationsMixin(EventGridPublisherClientMixinABC): async def _send( # pylint: disable=protected-access self, topic_name: str, event: _models._models.CloudEvent, **kwargs: Any ) -> _models._models.PublishResult: - # pylint: disable=line-too-long """Publish a single Cloud Event to a namespace topic. :param topic_name: Topic Name. Required. @@ -70,23 +71,16 @@ async def _send( # pylint: disable=protected-access # JSON input template you can fill out and use as your body input. event = { - "id": "str", # An identifier for the event. The combination of id and source - must be unique for each distinct event. Required. - "source": "str", # Identifies the context in which an event happened. The - combination of id and source must be unique for each distinct event. Required. - "specversion": "str", # The version of the CloudEvents specification which - the event uses. Required. - "type": "str", # Type of event related to the originating occurrence. - Required. - "data": {}, # Optional. Event data specific to the event type. - "data_base64": bytes("bytes", encoding="utf-8"), # Optional. Event data - specific to the event type, encoded as a base64 string. - "datacontenttype": "str", # Optional. Content type of data value. - "dataschema": "str", # Optional. Identifies the schema that data adheres to. - "subject": "str", # Optional. This describes the subject of the event in the - context of the event producer (identified by source). - "time": "2020-02-20 00:00:00" # Optional. The time (in UTC) the event was - generated, in RFC3339 format. + "id": "str", + "source": "str", + "specversion": "str", + "type": "str", + "data": {}, + "data_base64": bytes("bytes", encoding="utf-8"), + "datacontenttype": "str", + "dataschema": "str", + "subject": "str", + "time": "2020-02-20 00:00:00" } """ error_map: MutableMapping[int, Type[HttpResponseError]] = { @@ -129,7 +123,10 @@ async def _send( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -149,7 +146,6 @@ async def _send( # pylint: disable=protected-access async def _send_events( # pylint: disable=protected-access self, topic_name: str, events: List[_models._models.CloudEvent], **kwargs: Any ) -> _models._models.PublishResult: - # pylint: disable=line-too-long """Publish a batch of Cloud Events to a namespace topic. :param topic_name: Topic Name. Required. @@ -166,25 +162,16 @@ async def _send_events( # pylint: disable=protected-access # JSON input template you can fill out and use as your body input. events = [ { - "id": "str", # An identifier for the event. The combination of id - and source must be unique for each distinct event. Required. - "source": "str", # Identifies the context in which an event - happened. The combination of id and source must be unique for each distinct - event. Required. - "specversion": "str", # The version of the CloudEvents specification - which the event uses. Required. - "type": "str", # Type of event related to the originating - occurrence. Required. - "data": {}, # Optional. Event data specific to the event type. - "data_base64": bytes("bytes", encoding="utf-8"), # Optional. Event - data specific to the event type, encoded as a base64 string. - "datacontenttype": "str", # Optional. Content type of data value. - "dataschema": "str", # Optional. Identifies the schema that data - adheres to. - "subject": "str", # Optional. This describes the subject of the - event in the context of the event producer (identified by source). - "time": "2020-02-20 00:00:00" # Optional. The time (in UTC) the - event was generated, in RFC3339 format. + "id": "str", + "source": "str", + "specversion": "str", + "type": "str", + "data": {}, + "data_base64": bytes("bytes", encoding="utf-8"), + "datacontenttype": "str", + "dataschema": "str", + "subject": "str", + "time": "2020-02-20 00:00:00" } ] """ @@ -228,7 +215,10 @@ async def _send_events( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -257,7 +247,6 @@ async def _receive( # pylint: disable=protected-access max_wait_time: Optional[int] = None, **kwargs: Any ) -> _models._models.ReceiveResult: - # pylint: disable=line-too-long """Receive a batch of Cloud Events from a subscription. :param topic_name: Topic Name. Required. @@ -285,36 +274,20 @@ async def _receive( # pylint: disable=protected-access "value": [ { "brokerProperties": { - "deliveryCount": 0, # The attempt count for - delivering the event. Required. - "lockToken": "str" # The token of the lock on the - event. Required. + "deliveryCount": 0, + "lockToken": "str" }, "event": { - "id": "str", # An identifier for the event. The - combination of id and source must be unique for each distinct event. - Required. - "source": "str", # Identifies the context in which - an event happened. The combination of id and source must be unique - for each distinct event. Required. - "specversion": "str", # The version of the - CloudEvents specification which the event uses. Required. - "type": "str", # Type of event related to the - originating occurrence. Required. - "data": {}, # Optional. Event data specific to the - event type. - "data_base64": bytes("bytes", encoding="utf-8"), # - Optional. Event data specific to the event type, encoded as a base64 - string. - "datacontenttype": "str", # Optional. Content type - of data value. - "dataschema": "str", # Optional. Identifies the - schema that data adheres to. - "subject": "str", # Optional. This describes the - subject of the event in the context of the event producer (identified - by source). - "time": "2020-02-20 00:00:00" # Optional. The time - (in UTC) the event was generated, in RFC3339 format. + "id": "str", + "source": "str", + "specversion": "str", + "type": "str", + "data": {}, + "data_base64": bytes("bytes", encoding="utf-8"), + "datacontenttype": "str", + "dataschema": "str", + "subject": "str", + "time": "2020-02-20 00:00:00" } } ] @@ -356,7 +329,10 @@ async def _receive( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -436,7 +412,7 @@ async def _acknowledge( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -445,27 +421,22 @@ async def _acknowledge( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. + "str" ] } """ @@ -518,7 +489,10 @@ async def _acknowledge( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -533,9 +507,6 @@ async def _acknowledge( return deserialized # type: ignore @overload - @api_version_validation( - params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, - ) async def _release( self, topic_name: str, @@ -547,9 +518,6 @@ async def _release( **kwargs: Any ) -> _models.ReleaseResult: ... @overload - @api_version_validation( - params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, - ) async def _release( self, topic_name: str, @@ -561,9 +529,6 @@ async def _release( **kwargs: Any ) -> _models.ReleaseResult: ... @overload - @api_version_validation( - params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, - ) async def _release( self, topic_name: str, @@ -614,7 +579,7 @@ async def _release( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -623,27 +588,22 @@ async def _release( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. + "str" ] } """ @@ -697,7 +657,10 @@ async def _release( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -774,7 +737,7 @@ async def _reject( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -783,27 +746,22 @@ async def _reject( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. + "str" ] } """ @@ -856,7 +814,10 @@ async def _reject( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) @@ -871,12 +832,6 @@ async def _reject( return deserialized # type: ignore @overload - @api_version_validation( - method_added_on="2023-10-01-preview", - params_added_on={ - "2023-10-01-preview": ["api_version", "topic_name", "event_subscription_name", "content_type", "accept"] - }, - ) async def _renew_locks( self, topic_name: str, @@ -887,12 +842,6 @@ async def _renew_locks( **kwargs: Any ) -> _models.RenewLocksResult: ... @overload - @api_version_validation( - method_added_on="2023-10-01-preview", - params_added_on={ - "2023-10-01-preview": ["api_version", "topic_name", "event_subscription_name", "content_type", "accept"] - }, - ) async def _renew_locks( self, topic_name: str, @@ -903,12 +852,6 @@ async def _renew_locks( **kwargs: Any ) -> _models.RenewLocksResult: ... @overload - @api_version_validation( - method_added_on="2023-10-01-preview", - params_added_on={ - "2023-10-01-preview": ["api_version", "topic_name", "event_subscription_name", "content_type", "accept"] - }, - ) async def _renew_locks( self, topic_name: str, @@ -958,7 +901,7 @@ async def _renew_locks( # JSON input template you can fill out and use as your body input. body = { "lockTokens": [ - "str" # Array of lock tokens. Required. + "str" ] } @@ -967,27 +910,22 @@ async def _renew_locks( "failedLockTokens": [ { "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. + "code": "str", + "message": "str", "details": [ ... ], "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. + "code": "str", "innererror": ... }, - "target": "str" # Optional. The target of the error. + "target": "str" }, - "lockToken": "str" # The lock token of an entry in the - request. Required. + "lockToken": "str" } ], "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. + "str" ] } """ @@ -1040,7 +978,10 @@ async def _renew_locks( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + 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) raise HttpResponseError(response=response) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py index 8b9dcb1760cb..a552fe3c3125 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py @@ -15,6 +15,7 @@ DataType = TypeVar("DataType") + class ReceiveDetails(InternalReceiveDetails, Generic[DataType]): """Receive operation details per Cloud Event. diff --git a/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_publish_cncf_events_async.py b/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_publish_cncf_events_async.py index d8b641ddf627..24bf463e44a3 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_publish_cncf_events_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/namespace/async_samples/sample_publish_cncf_events_async.py @@ -34,7 +34,11 @@ async def publish(): await client.send( [ CloudEvent( - attributes={"type": "cloudevent", "source": "/cncf/cloud/event/1.0", "subject": "testing-cncf-event"}, + attributes={ + "type": "cloudevent", + "source": "/cncf/cloud/event/1.0", + "subject": "testing-cncf-event", + }, data=b"This is a cncf cloud event.", ) ] diff --git a/sdk/eventgrid/azure-eventgrid/tsp-location.yaml b/sdk/eventgrid/azure-eventgrid/tsp-location.yaml index 54fc7682d014..49ce134822bd 100644 --- a/sdk/eventgrid/azure-eventgrid/tsp-location.yaml +++ b/sdk/eventgrid/azure-eventgrid/tsp-location.yaml @@ -1,4 +1,4 @@ -cleanup: false -commit: 25afa22a250c0ad5a28671003f961b9cd20d60f6 directory: specification/eventgrid/Azure.Messaging.EventGrid -repo: Azure/azure-rest-api-specs \ No newline at end of file +commit: f69147628e524f70bdf7ada9a84461bfa546b5a5 +repo: Azure/azure-rest-api-specs +additionalDirectories: