Exemple #1
0
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_event_grid_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)
     eg_event1 = EventGridEvent(subject="sample",
                                data="eventgridevent",
                                event_type="Sample.EventGrid.Event",
                                data_version="2.0")
     eg_event2 = EventGridEvent(subject="sample2",
                                data="eventgridevent2",
                                event_type="Sample.EventGrid.Event",
                                data_version="2.0")
     client.send([eg_event1, eg_event2])
 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
Exemple #4
0
 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)
Exemple #5
0
 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_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_custom_schema_event_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)
     custom_event1 = {
                 "customSubject": "sample",
                 "customEventType": "sample.event",
                 "customDataVersion": "2.0",
                 "customId": "1234",
                 "customEventTime": dt.datetime.now(UTC()).isoformat(),
                 "customData": "sample data"
                 }
     custom_event2 = {
                 "customSubject": "sample2",
                 "customEventType": "sample.event",
                 "customDataVersion": "2.0",
                 "customId": "12345",
                 "customEventTime": dt.datetime.now(UTC()).isoformat(),
                 "customData": "sample data 2"
                 }
     client.send([custom_event1, custom_event2])
Exemple #8
0
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')
    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)
Exemple #10
0
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]
"""
FILE: sample_publish_events_using_cloud_events_1.0_schema.py
DESCRIPTION:
    These samples demonstrate creating a list of CloudEvents and sending then as a list.
USAGE:
    python sample_publish_events_using_cloud_events_1.0_schema.py
    Set the environment variables with your own values before running the sample:
    1) CLOUD_ACCESS_KEY - The access key of your eventgrid account.
    2) CLOUD_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format
    "<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net".
"""
# [START publish_cloud_event_to_topic]
import os
from azure.eventgrid import EventGridPublisherClient
from azure.core.credentials import AzureKeyCredential
from azure.core.messaging import CloudEvent

topic_key = os.environ["CLOUD_ACCESS_KEY"]
endpoint = os.environ["CLOUD_TOPIC_HOSTNAME"]

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")
])
# [END publish_cloud_event_to_topic]
Exemple #12
0
domain_key = os.environ["DOMAIN_ACCESS_KEY"]
domain_topic_hostname = os.environ["DOMAIN_TOPIC_HOSTNAME"]
domain_name = os.environ["DOMAIN_NAME"]

# authenticate client
credential = AzureKeyCredential(domain_key)
client = EventGridPublisherClient(domain_topic_hostname, credential)

# publish events
while True:

    event_list = []  # list of events to publish
    team_members = [
        "Josh", "Kerri", "Kieran", "Laurent", "Lily", "Matt", "Soren",
        "Srikanta", "Swathi"
    ]  # possible values for data field

    # create events and append to list
    for j in range(randint(1, 3)):
        sample_members = sample(team_members, k=randint(
            1, 9))  # select random subset of team members
        event = CloudEvent(type="Azure.Sdk.Demo",
                           source=domain_name,
                           data={"team": sample_members})
        event_list.append(event)

    # publish list of events
    client.send(event_list)
    print("Batch of size {} published".format(len(event_list)))
    time.sleep(randint(1, 5))
    and sending them as a list.
USAGE:
    python sample_publish_cloud_event_using_dict.py
    Set the environment variables with your own values before running the sample:
    1) EVENTGRID_CLOUD_EVENT_TOPIC_KEY - The access key of your eventgrid account.
    2) EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT - 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
from azure.core.credentials import AzureKeyCredential

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)

# [START publish_cloud_event_dict]
client.send([{
    "type": "Contoso.Items.ItemReceived",
    "source": "/contoso/items",
    "data": {
        "itemSku": "Contoso Item SKU #1"
    },
    "subject": "Door1",
    "specversion": "1.0",
    "id": "randomclouduuid11"
}])
# [END publish_cloud_event_dict]
Exemple #14
0
class EventGridPerfTest(PerfStressTest):
    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"))

    async def close(self):
        """This is run after cleanup.
        
        Use this to close any open handles or clients.
        """
        await self.async_publisher_client.close()
        await super().close()

    def run_sync(self):
        """The synchronous perf test.
        
        Try to keep this minimal and focused. Using only a single client API.
        Avoid putting any ancilliary logic (e.g. generating UUIDs), and put this in the setup/init instead
        so that we're only measuring the client API call.
        """
        self.publisher_client.send(self.event_list)

    async def run_async(self):
        """The asynchronous perf test.
        
        Try to keep this minimal and focused. Using only a single client API.
        Avoid putting any ancilliary logic (e.g. generating UUIDs), and put this in the setup/init instead
        so that we're only measuring the client API call.
        """
        await self.async_publisher_client.send(self.event_list)

    @staticmethod
    def add_arguments(parser):
        super(EventGridPerfTest, EventGridPerfTest).add_arguments(parser)
        parser.add_argument(
            '-n',
            '--num-events',
            nargs='?',
            type=int,
            help='Number of events to be sent. Defaults to 100',
            default=100)
# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python
# for details
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
from opentelemetry.sdk.trace.export import SimpleExportSpanProcessor

# Simple console exporter
exporter = ConsoleSpanExporter()

trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
trace.get_tracer_provider().add_span_processor(
    SimpleExportSpanProcessor(exporter))

# Example with Eventgrid SDKs
import os
from azure.eventgrid import EventGridPublisherClient, CloudEvent
from azure.core.credentials import AzureKeyCredential

hostname = os.environ['CLOUD_TOPIC_HOSTNAME']
key = AzureKeyCredential(os.environ['CLOUD_ACCESS_KEY'])
cloud_event = CloudEvent(source='demo',
                         type='sdk.demo',
                         data={'test': 'hello'},
                         extensions={'test': 'maybe'})
with tracer.start_as_current_span(name="MyApplication"):
    client = EventGridPublisherClient(hostname, key)
    client.send(cloud_event)
Exemple #16
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")
])
    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")
])
Exemple #18
0
DESCRIPTION:
    This sample demonstrates creating sending a cloud event from the CNCF library.
USAGE:
    python sample_publish_cncf_cloud_events.py
    Set the environment variables with your own values before running the sample:
    1) CLOUD_ACCESS_KEY - The access key of your eventgrid account.
    2) CLOUD_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
from azure.core.credentials import AzureKeyCredential
from cloudevents.http import CloudEvent

topic_key = os.environ["CLOUD_ACCESS_KEY"]
endpoint = os.environ["CLOUD_TOPIC_HOSTNAME"]

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

client.send([
    CloudEvent(
        attributes={
            "type": "cloudevent",
            "source": "/cncf/cloud/event/1.0",
            "subject": "testingcncfevent"
        },
        data=b'This is a cncf cloud event.',
    )
])