def publish(): # [START publish_eg_event_dict] 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])
def publish_event(): # authenticate client credential = AzureKeyCredential(key) client = EventGridPublisherClient(endpoint, credential) custom_schema_event = { "customSubject": "sample", "customEventType": "sample.event", "customDataVersion": "2.0", "customId": uuid.uuid4(), "customEventTime": dt.datetime.now(UTC()).isoformat(), "customData": "sample data" } # publish events for _ in range(3): event_list = [] # list of events to publish # create events and append to list for j in range(randint(1, 3)): event_list.append(custom_schema_event) # publish list of events client.send(event_list) print("Batch of size {} published".format(len(event_list))) time.sleep(randint(1, 5))
def test_send_token_credential(self, variables, eventgrid_topic_endpoint): credential = self.get_credential(EventGridPublisherClient) client = EventGridPublisherClient(eventgrid_topic_endpoint, credential) eg_event = EventGridEvent(subject="sample", data={"sample": "eventgridevent"}, event_type="Sample.EventGrid.Event", data_version="2.0") client.send(eg_event)
def test_send_cloud_event_data_as_list(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) cloud_event = CloudEvent( source = "http://samplesource.dev", data = "cloudevent", type="Sample.Cloud.Event" ) client.send([cloud_event])
def test_send_event_grid_event_data_str(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) eg_event = EventGridEvent( subject="sample", data=u"eventgridevent", event_type="Sample.EventGrid.Event", data_version="2.0" ) client.send(eg_event)
def test_send_event_grid_event_fails_without_full_url( self, variables, eventgrid_topic_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_key) parsed_url = urlparse(eventgrid_topic_endpoint) client = EventGridPublisherClient(parsed_url.netloc, akc_credential) eg_event = EventGridEvent(subject="sample", data={"sample": "eventgridevent"}, event_type="Sample.EventGrid.Event", data_version="2.0") with pytest.raises(ValueError): client.send(eg_event)
def test_send_event_grid_event_data_bytes(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) eg_event = EventGridEvent( subject="sample", data=b"eventgridevent", event_type="Sample.EventGrid.Event", data_version="2.0" ) with pytest.raises(TypeError, match="Data in EventGridEvent cannot be bytes*"): client.send(eg_event)
def test_raise_on_bad_resource(self, variables, eventgrid_topic_key): akc_credential = AzureKeyCredential(eventgrid_topic_key) client = EventGridPublisherClient( "https://bad-resource.westus-1.eventgrid.azure.net/api/events", akc_credential) eg_event = EventGridEvent(subject="sample", data={"sample": "eventgridevent"}, event_type="Sample.EventGrid.Event", data_version="2.0") with pytest.raises(HttpResponseError): client.send(eg_event)
def test_send_cloud_event_dict(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) cloud_event1 = { "id": "1234", "source": "http://samplesource.dev", "specversion": "1.0", "data": "cloudevent", "type": "Sample.Cloud.Event" } client.send(cloud_event1)
def test_send_signature_credential(self, variables, eventgrid_topic_key, eventgrid_topic_endpoint): expiration_date_utc = dt.datetime.now(UTC()) + timedelta(hours=1) signature = generate_sas(eventgrid_topic_endpoint, eventgrid_topic_key, expiration_date_utc) credential = AzureSasCredential(signature) client = EventGridPublisherClient(eventgrid_topic_endpoint, credential) eg_event = EventGridEvent(subject="sample", data={"sample": "eventgridevent"}, event_type="Sample.EventGrid.Event", data_version="2.0") client.send(eg_event)
def test_send_event_grid_event_dict_data_dict(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) eg_event = { "subject":"sample", "data":{"key1": "Sample.EventGrid.Event"}, "eventType":"Sample.EventGrid.Event", "dataVersion":"2.0", "id": uuid.uuid4(), "eventTime": datetime.now() } client.send(eg_event)
def test_raise_on_auth_error(self, variables, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential("bad credential") client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) eg_event = EventGridEvent(subject="sample", data={"sample": "eventgridevent"}, event_type="Sample.EventGrid.Event", data_version="2.0") with pytest.raises( ClientAuthenticationError, match="The request authorization key is not authorized for*"): client.send(eg_event)
def test_send_custom_schema_event(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) custom_event = { "customSubject": "sample", "customEventType": "sample.event", "customDataVersion": "2.0", "customId": "1234", "customEventTime": dt.datetime.now(UTC()).isoformat(), "customData": "sample data" } client.send(custom_event)
def test_send_cloud_event_data_none(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", } data = None cloud_event = CloudEvent(attributes, data) client.send(cloud_event)
def test_send_event_grid_event_dict_data_bytes(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) eg_event = { "subject":"sample", "data":b"eventgridevent", "eventType":"Sample.EventGrid.Event", "dataVersion":"2.0", "id": uuid.uuid4(), "eventTime": datetime.now() } with pytest.raises(TypeError, match="Data in EventGridEvent cannot be bytes*"): client.send(eg_event)
def test_send_cloud_event_data_NULL(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) cloud_event = CloudEvent( source = "http://samplesource.dev", data = NULL, type="Sample.Cloud.Event" ) def callback(request): req = json.loads(request.http_request.body) assert req[0].get("data") is None client.send(cloud_event, raw_request_hook=callback)
def test_send_signature_credential(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): expiration_date_utc = dt.datetime.now(UTC()) + timedelta(hours=1) signature = generate_shared_access_signature( eventgrid_topic_endpoint, eventgrid_topic_primary_key, expiration_date_utc) credential = EventGridSharedAccessSignatureCredential(signature) client = EventGridPublisherClient(eventgrid_topic_endpoint, credential) eg_event = EventGridEvent(subject="sample", data={"sample": "eventgridevent"}, event_type="Sample.EventGrid.Event", data_version="2.0") client.send(eg_event)
def test_send_cloud_event_data_with_extensions(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", "ext1": "extension" } data = "hello world" cloud_event = CloudEvent(attributes, data) client.send([cloud_event])
def test_send_NONE_credential(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): with pytest.raises( ValueError, match="Parameter 'self._credential' must not be None."): client = EventGridPublisherClient(eventgrid_topic_endpoint, None)
def publish_event(): # authenticate client credential = AzureKeyCredential(key) client = EventGridPublisherClient(endpoint, credential) # [START publish_custom_schema] 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)
def test_send_cloud_event_data_with_extensions(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) cloud_event = CloudEvent( source = "http://samplesource.dev", data = "cloudevent", type="Sample.Cloud.Event", extensions={ 'reasoncode':204, 'extension':'hello' } ) client.send([cloud_event]) internal = _cloud_event_to_generated(cloud_event).serialize() assert 'reasoncode' in internal assert 'extension' in internal assert internal['reasoncode'] == 204
def test_send_throws_with_bad_credential(self): bad_credential = "I am a bad credential" with pytest.raises( ValueError, match= "The provided credential should be an instance of a TokenCredential, AzureSasCredential or AzureKeyCredential" ): client = EventGridPublisherClient("eventgrid_endpoint", bad_credential)
def test_send_cloud_event_data_str(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", } data = "hello world" def callback(request): req = json.loads(request.http_request.body) assert req[0].get("data_base64") is None assert req[0].get("data") is not None cloud_event = CloudEvent(attributes, data) client.send(cloud_event, raw_request_hook=callback)
def test_send_cloud_event_data_dict(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint): akc_credential = AzureKeyCredential(eventgrid_topic_primary_key) client = EventGridPublisherClient(eventgrid_topic_endpoint, akc_credential) attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", } data = {"message": "Hello World!"} cloud_event = CloudEvent(attributes, data) def callback(request): req = json.loads(request.http_request.body) assert req[0].get("data") is not None assert isinstance(req[0], dict) assert req[0].get("type") == "com.example.sampletype1" assert req[0].get("source") == "https://example.com/event-producer" client.send(cloud_event, raw_request_hook=callback)
def main(): # Read configuration information config_dict = loadcfg() cfg_event_grid_topic_key = config_dict['eventgridtopickey'] cfg_event_grid_topic_endpoint = config_dict['eventgridtopicendpoint'] event = EventGridEvent(data={ "make": "Audi", "model": "Q5" }, subject="myapp/vehicles/cars", event_type="recordInserted", data_version="1.0") credential = AzureKeyCredential(cfg_event_grid_topic_key) print('Sending event to Event Grid Topic ...') client = EventGridPublisherClient(cfg_event_grid_topic_endpoint, credential) # Send event client.send(event) print('Sent')
class EventGrid: def __init__(self): self.subscriptions = {} self.client = EventGridPublisherClient(event_grid_endpoint, AzureKeyCredential(event_grid_key)) def publish(self, topic, message=''): try: print(f'event_grid.publish({topic}, {message})') event = EventGridEvent(data=message, subject=topic, event_type="mobil-e-hub", data_version="1.0") self.client.send(event) except Error as err: print(err) def receive(self, event): # Decompose event topic = event['subject'] message = event['data'] entity, id, *args = topic.split('/') topic = { 'entity': entity, 'id': id, 'args': args, 'rest': '/'.join(args), 'string': topic } print(f'> (opt) {topic["string"]}: {message}') # Call matching subscriptions for pattern, handlers in self.subscriptions.items(): if match_topic(pattern, topic['string']): for handler in handlers: handler(topic, message) def subscribe(self, pattern, handler): if pattern in self.subscriptions: self.subscriptions[pattern].append(handler) else: self.subscriptions[pattern] = [handler] def unsubscribe(self, pattern, handler): if pattern in self.subscriptions: self.subscriptions[pattern].remove(handler) if len(self.subscriptions[pattern]) == 0: del self.subscriptions[pattern]
def __init__(self, arguments): super().__init__(arguments) # auth configuration topic_key = self.get_from_env("EG_ACCESS_KEY") endpoint = self.get_from_env("EG_TOPIC_HOSTNAME") # Create clients self.publisher_client = SyncPublisherClient( endpoint=endpoint, credential=AzureKeyCredential(topic_key)) self.async_publisher_client = AsyncPublisherClient( endpoint=endpoint, credential=AzureKeyCredential(topic_key)) self.event_list = [] for _ in range(self.args.num_events): self.event_list.append( EventGridEvent( event_type="Contoso.Items.ItemReceived", data={ "services": ["EventGrid", "ServiceBus", "EventHubs", "Storage"] }, subject="Door1", data_version="2.0"))
2) CLOUD_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format "<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net". """ import os from random import randint, sample import time from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridPublisherClient, CloudEvent key = os.environ.get("CLOUD_ACCESS_KEY") topic_hostname = os.environ["CLOUD_TOPIC_HOSTNAME"] # authenticate client credential = AzureKeyCredential(key) client = EventGridPublisherClient(topic_hostname, credential) team_members = [ "Josh", "Kerri", "Kieran", "Laurent", "Lily", "Matt", "Soren", "Srikanta", "Swathi" ] # possible values for data field def publish_event(): # publish events for _ in range(10): event_list = [] # list of events to publish # create events and append to list for j in range(randint(1, 1)): sample_members = sample(team_members, k=randint( 1, 9)) # select random subset of team members
These samples demonstrate creating a list of EventGrid Events and sending them as a list to a topic in a domain. USAGE: python sample_publish_eg_events_to_a_domain.py Set the environment variables with your own values before running the sample: 1) EG_ACCESS_KEY - The access key of your eventgrid account. 2) EG_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format "https://<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net/api/events". """ import os from azure.eventgrid import EventGridPublisherClient, EventGridEvent from azure.core.credentials import AzureKeyCredential domain_key = os.environ["EG_DOMAIN_ACCESS_KEY"] domain_hostname = os.environ["EG_DOMAIN_TOPIC_HOSTNAME"] credential = AzureKeyCredential(domain_key) client = EventGridPublisherClient(domain_hostname, credential) client.send([ EventGridEvent(topic="MyCustomDomainTopic1", event_type="Contoso.Items.ItemReceived", data={"itemSku": "Contoso Item SKU #1"}, subject="Door1", data_version="2.0"), EventGridEvent(topic="MyCustomDomainTopic2", event_type="Contoso.Items.ItemReceived", data={"itemSku": "Contoso Item SKU #2"}, subject="Door1", data_version="2.0") ])
# license information. # -------------------------------------------------------------------------- """ FILE: sample_publish_events_to_a_topic_using_sas_credential.py DESCRIPTION: These samples demonstrate sending an EventGrid Event using a shared access signature for authentication. USAGE: python sample_publish_events_to_a_topic_using_sas_credential.py Set the environment variables with your own values before running the sample: 1) EVENTGRID_SAS - The shared access signature to use Event Grid. This is typically given to you after creating it using the `generate_sas` method. 2) EG_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format "https://<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net/api/events". """ import os from azure.eventgrid import EventGridPublisherClient, EventGridEvent, generate_sas from azure.core.credentials import AzureKeyCredential, AzureSasCredential sas = os.environ["EVENTGRID_SAS"] endpoint = os.environ["EG_TOPIC_HOSTNAME"] credential = AzureSasCredential(sas) client = EventGridPublisherClient(endpoint, credential) client.send([ EventGridEvent(event_type="Contoso.Items.ItemReceived", data={"itemSku": "Contoso Item SKU #1"}, subject="Door1", data_version="2.0") ])