azure.eventgrid package

class azure.eventgrid.EventGridEvent(subject: str, event_type: str, data: object, data_version: str, **kwargs: Any)[source]

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.

Parameters
  • subject (str) – Required. A resource path relative to the topic path.

  • event_type (str) – Required. The type of the event that occurred.

  • data (object) – Required. Event data specific to the event type.

  • data_version (str) – Required. The schema version of the data object. If not provided, will be stamped with an empty value.

Keyword Arguments
  • topic (Optional[str]) – 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.

  • metadata_version (Optional[str]) – The schema version of the event metadata. If provided, must match Event Grid Schema exactly. If not provided, EventGrid will stamp onto event.

  • id (Optional[str]) – An identifier for the event. In not provided, a random UUID will be generated and used.

  • event_time (Optional[datetime]) – The time (in UTC) of the event. If not provided, it will be the time (in UTC) the event was generated.

Variables
  • subject (str) – A resource path relative to the topic path.

  • event_type (str) – The type of the event that occurred.

  • data (object) – Event data specific to the event type.

  • data_version (str) – The schema version of the data object. If not provided, will be stamped with an empty value.

  • topic (str) – The resource path of the event source. If not provided, Event Grid will stamp onto the event.

  • metadata_version (str) – The schema version of the event metadata. If provided, must match Event Grid Schema exactly. If not provided, EventGrid will stamp onto event.

  • id (str) – An identifier for the event. In not provided, a random UUID will be generated and used.

  • event_time (datetime) – The time (in UTC) of the event. If not provided, it will be the time (in UTC) the event was generated.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

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.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

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)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod from_json(event: Any)azure.eventgrid._models.EventGridEvent[source]

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

Return type

EventGridEvent

Raises

ValueError – If the provided JSON is invalid.

classmethod is_xml_model()
serialize(keep_readonly=False, **kwargs)

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.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.eventgrid.EventGridPublisherClient(endpoint: str, credential: Union[AzureKeyCredential, AzureSasCredential, TokenCredential], **kwargs: Any)[source]

EventGridPublisherClient publishes events to an EventGrid topic or domain. It can be used to publish either an EventGridEvent, a CloudEvent or a Custom Schema.

Parameters
  • endpoint (str) – The topic endpoint to send the events to.

  • credential (AzureKeyCredential or AzureSasCredential or TokenCredential) – The credential object used for authentication which implements SAS key authentication or SAS token authentication or a TokenCredential.

Return type

None

Example:

Creating the EventGridPublisherClient with an endpoint and AzureKeyCredential.
import os
from azure.eventgrid import EventGridPublisherClient
from azure.core.credentials import AzureKeyCredential

topic_key = os.environ["EVENTGRID_TOPIC_KEY"]
endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]

credential = AzureKeyCredential(topic_key)
client = EventGridPublisherClient(endpoint, credential)
Creating the EventGridPublisherClient with an endpoint and AzureSasCredential.
import os
from azure.eventgrid import EventGridPublisherClient
from azure.core.credentials import AzureSasCredential

signature = os.environ["EVENTGRID_SAS"]
endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]

credential = AzureSasCredential(signature)
client = EventGridPublisherClient(endpoint, credential)
close()None[source]

Close the EventGridPublisherClient session.

send(events: Union[azure.core.messaging.CloudEvent, azure.eventgrid._models.EventGridEvent, Dict, List[azure.core.messaging.CloudEvent], List[azure.eventgrid._models.EventGridEvent], List[Dict]], *, channel_name: Optional[str] = None, **kwargs: Any)None[source]

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.

Example:

Publishing an EventGridEvent.
import os
from azure.eventgrid import EventGridPublisherClient, EventGridEvent
from azure.core.credentials import AzureKeyCredential

topic_key = os.environ["EVENTGRID_TOPIC_KEY"]
endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]

credential = AzureKeyCredential(topic_key)
client = EventGridPublisherClient(endpoint, credential)

client.send([
	EventGridEvent(
		event_type="Contoso.Items.ItemReceived",
		data={
			"itemSku": "Contoso Item SKU #1"
		},
		subject="Door1",
		data_version="2.0"
	)
])
Publishing a CloudEvent.
import os
from azure.eventgrid import EventGridPublisherClient
from azure.core.credentials import AzureKeyCredential
from azure.core.messaging import CloudEvent

topic_key = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_KEY"]
endpoint = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT"]

credential = AzureKeyCredential(topic_key)
client = EventGridPublisherClient(endpoint, credential)

client.send([
    CloudEvent(
        type="Contoso.Items.ItemReceived",
        source="/contoso/items",
        data={
            "itemSku": "Contoso Item SKU #1"
        },
        subject="Door1"
    )
])

Dict representation of respective serialized models is accepted as CloudEvent(s) or EventGridEvent(s) apart from the strongly typed objects.

Example:

Publishing a list of EventGridEvents using a dict-like representation.
credential = AzureKeyCredential(topic_key)
client = EventGridPublisherClient(endpoint, credential)

event0 = {	
    "eventType": "Contoso.Items.ItemReceived",	
    "data": {	
        "itemSku": "Contoso Item SKU #1"	
    },	
    "subject": "Door1",	
    "dataVersion": "2.0",	
    "id": "randomuuid11",	
    "eventTime": datetime.now(UTC())
}	
event1 = {	
    "eventType": "Contoso.Items.ItemReceived",	
    "data": {	
        "itemSku": "Contoso Item SKU #2"	
    },	
    "subject": "Door1",	
    "dataVersion": "2.0",	
    "id": "randomuuid12",	
    "eventTime": datetime.now(UTC())
}	
client.send([event0, event1])
Publishing a CloudEvent using a dict-like representation.
client.send([
    {
        "type": "Contoso.Items.ItemReceived",
        "source": "/contoso/items",	
        "data": {	
            "itemSku": "Contoso Item SKU #1"	
        },	
        "subject": "Door1",	
        "specversion": "1.0",	
        "id": "randomclouduuid11"
    }
])

When publishing a Custom Schema Event(s), dict-like representation is accepted. Either a single dictionary or a list of dictionaries can be passed.

Example:

Publishing a Custom Schema event.
custom_schema_event = {
    "customSubject": "sample",
    "customEventType": "sample.event",
    "customDataVersion": "2.0",
    "customId": uuid.uuid4(),
    "customEventTime": dt.datetime.now(UTC()).isoformat(),
    "customData": "sample data"
}

client.send(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.

Parameters

events (CloudEvent or EventGridEvent or dict or List[CloudEvent] or List[EventGridEvent] or List[dict]) – A single instance or a list of dictionaries/CloudEvent/EventGridEvent to be sent.

Keyword Arguments
  • content_type (str) – 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

  • channel_name (str) – Optional. Used to specify the name of event channel when publishing to partner. namespaces with partner topic. For more details, visit https://docs.microsoft.com/azure/event-grid/partner-events-overview

Return type

None

class azure.eventgrid.SystemEventNames(value)[source]

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.

AcsChatMemberAddedToThreadWithUserEventName = 'Microsoft.Communication.ChatMemberAddedToThreadWithUser'
AcsChatMemberRemovedFromThreadWithUserEventName = 'Microsoft.Communication.ChatMemberRemovedFromThreadWithUser'
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'
AcsChatThreadParticipantAddedEventName = 'Microsoft.Communication.ChatThreadParticipantAdded'
AcsChatThreadParticipantRemovedEventName = 'Microsoft.Communication.ChatThreadParticipantRemoved'
AcsChatThreadPropertiesUpdatedEventName = 'Microsoft.Communication.ChatThreadPropertiesUpdated'
AcsChatThreadPropertiesUpdatedPerUserEventName = 'Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser'
AcsChatThreadWithUserDeletedEventName = 'Microsoft.Communication.ChatThreadWithUserDeleted'
AcsRecordingFileStatusUpdatedEventName = 'Microsoft.Communication.RecordingFileStatusUpdated'
AcsSmsDeliveryReportReceivedEventName = 'Microsoft.Communication.SMSDeliveryReportReceived'
AcsSmsReceivedEventName = 'Microsoft.Communication.SMSReceived'
AcsUserDisconnectedEventName = 'Microsoft.Communication.UserDisconnected'
ApiManagementApiCreatedEventName = 'Microsoft.ApiManagement.ApiCreated'
ApiManagementApiDeletedEventName = 'Microsoft.ApiManagement.ApiDeleted'
ApiManagementApiReleaseCreatedEventName = 'Microsoft.ApiManagement.ApiReleaseCreated'
ApiManagementApiReleaseDeletedEventName = 'Microsoft.ApiManagement.ApiReleaseDeleted'
ApiManagementApiReleaseUpdatedEventName = 'Microsoft.ApiManagement.ApiReleaseUpdated'
ApiManagementApiUpdatedEventName = 'Microsoft.ApiManagement.ApiUpdated'
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'
ContainerRegistryArtifactEventName = 'Microsoft.AppConfiguration.KeyValueModified'
ContainerRegistryChartDeletedEventName = 'Microsoft.ContainerRegistry.ChartDeleted'
ContainerRegistryChartPushedEventName = 'Microsoft.ContainerRegistry.ChartPushed'
ContainerRegistryEventName = 'Microsoft.ContainerRegistry.ChartPushed'
ContainerRegistryImageDeletedEventName = 'Microsoft.ContainerRegistry.ImageDeleted'
ContainerRegistryImagePushedEventName = 'Microsoft.ContainerRegistry.ImagePushed'
ContainerServiceNewKubernetesVersionAvailableEventName = 'Microsoft.ContainerService.NewKubernetesVersionAvailable'
EventGridSubscriptionDeletedEventName = 'Microsoft.EventGrid.SubscriptionDeletedEvent'
EventGridSubscriptionValidationEventName = 'Microsoft.EventGrid.SubscriptionValidationEvent'
EventHubCaptureFileCreatedEventName = 'Microsoft.EventHub.CaptureFileCreated'
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'
IotHubDeviceConnectedEventName = 'Microsoft.Devices.DeviceConnected'
IotHubDeviceCreatedEventName = 'Microsoft.Devices.DeviceCreated'
IotHubDeviceDeletedEventName = 'Microsoft.Devices.DeviceDeleted'
IotHubDeviceDisconnectedEventName = 'Microsoft.Devices.DeviceDisconnected'
IotHubDeviceTelemetryEventName = 'Microsoft.Devices.DeviceTelemetry'
KeyVaultAccessPolicyChangedEventName = 'Microsoft.KeyVault.VaultAccessPolicyChanged'
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'
ResourceActionCancelEventName = 'Microsoft.Resources.ResourceActionCancel'
ResourceActionCancelName = 'Microsoft.Resources.ResourceActionCancel'
ResourceActionFailureEventName = 'Microsoft.Resources.ResourceActionFailure'
ResourceActionFailureName = 'Microsoft.Resources.ResourceActionFailure'
ResourceActionSuccessEventName = 'Microsoft.Resources.ResourceActionSuccess'
ResourceActionSuccessName = 'Microsoft.Resources.ResourceActionSuccess'
ResourceDeleteCancelEventName = 'Microsoft.Resources.ResourceDeleteCancel'
ResourceDeleteCancelName = 'Microsoft.Resources.ResourceDeleteCancel'
ResourceDeleteFailureEventName = 'Microsoft.Resources.ResourceDeleteFailure'
ResourceDeleteFailureName = 'Microsoft.Resources.ResourceDeleteFailure'
ResourceDeleteSuccessEventName = 'Microsoft.Resources.ResourceDeleteSuccess'
ResourceDeleteSuccessName = 'Microsoft.Resources.ResourceDeleteSuccess'
ResourceWriteCancelEventName = 'Microsoft.Resources.ResourceWriteCancel'
ResourceWriteCancelName = 'Microsoft.Resources.ResourceWriteCancel'
ResourceWriteFailureEventName = 'Microsoft.Resources.ResourceWriteFailure'
ResourceWriteFailureName = 'Microsoft.Resources.ResourceWriteFailure'
ResourceWriteSuccessEventName = 'Microsoft.Resources.ResourceWriteSuccess'
ResourceWriteSuccessName = 'Microsoft.Resources.ResourceWriteSuccess'
ServiceBusActiveMessagesAvailablePeriodicNotificationsEventName = 'Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications'
ServiceBusActiveMessagesAvailableWithNoListenersEventName = 'Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners'
ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventName = 'Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications'
ServiceBusDeadletterMessagesAvailableWithNoListenerEventName = 'Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners'
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'
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'
azure.eventgrid.generate_sas(endpoint: str, shared_access_key: str, expiration_date_utc: datetime, **kwargs: Any)str[source]

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 <YOUR-TOPIC-NAME>.<YOUR-REGION-NAME>-1.eventgrid.azure.net

Parameters
  • shared_access_key (str) – The shared access key to be used for generating the token

  • expiration_date_utc (datetime.datetime) – The expiration datetime in UTC for the signature.

Keyword Arguments

api_version (str) – The API Version to include in the signature. If not provided, the default API version will be used.

Return type

str

Example:

Generate a shared access signature.
import os
from azure.eventgrid import generate_sas
from datetime import datetime, timedelta

topic_key = os.environ["EVENTGRID_TOPIC_KEY"]
endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"]

#represents the expiration date for sas
expiration_date_utc = datetime.utcnow() + timedelta(hours=10)

signature = generate_sas(endpoint, topic_key, expiration_date_utc)