Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EG - add samples to docstrings #16873

Merged
merged 8 commits into from
Feb 23, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions sdk/eventgrid/azure-eventgrid/azure/eventgrid/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ def generate_sas(endpoint, shared_access_key, expiration_date_utc, **kwargs):
:keyword str api_version: The API Version to include in the signature.
If not provided, the default API version will be used.
:rtype: str

.. admonition:: Example:

.. literalinclude:: ../samples/sync_samples/sample_generate_sas.py
:start-after: [START generate_sas]
:end-before: [END generate_sas]
:language: python
:dedent: 8
:caption: Generate a shared access signature.
"""

full_endpoint = _get_full_endpoint(endpoint)
Expand Down
82 changes: 74 additions & 8 deletions sdk/eventgrid/azure-eventgrid/azure/eventgrid/_publisher_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,29 @@


class EventGridPublisherClient(object):
"""EventGrid Python Publisher Client.
"""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.
:type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential

.. admonition:: Example:

.. literalinclude:: ../samples/sync_samples/sample_authentication.py
:start-after: [START client_auth_with_key_cred]
:end-before: [END client_auth_with_key_cred]
:language: python
:dedent: 8
:caption: Creating the EventGridPublisherClient with an endpoint and AzureKeyCredential.

.. literalinclude:: ../samples/sync_samples/sample_authentication.py
:start-after: [START client_auth_with_sas_cred]
:end-before: [END client_auth_with_sas_cred]
:language: python
:dedent: 8
:caption: Creating the EventGridPublisherClient with an endpoint and AzureSasCredential.
"""

def __init__(self, endpoint, credential, **kwargs):
Expand Down Expand Up @@ -98,18 +115,67 @@ def _policies(credential, **kwargs):
@distributed_trace
def send(self, events, **kwargs):
# type: (SendType, Any) -> None
"""Sends event data to topic hostname specified during client initialization.
Multiple events can be published at once by seding a list of events. It is very
inefficient to loop the send method for each event instead of just using a list
and we highly recommend against it.

:param events: A list of CloudEvent/EventGridEvent to be sent.
"""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: 8
: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: 8
:caption: Publishing a CloudEvent.

A dict representation of respective serialized models can be used to send CloudEvent(s) or
EventGridEvent(s) instead of 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: 8
:caption: Publishing an EventGridEvent 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: 8
:caption: Publishing a CloudEvent using a dict-like representation.

When publishing a Custom schema event(s), a 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: 8
:caption: Publishing a Custom Schema event.

**WARNING**: To send multiple events at once, a list of events must be used.
It is very inefficient to loop the send method for each event instead of just
using a list and we highly recommend against it.

:param events: A single event or a list of dictionaries/CloudEvent/EventGridEvent to be sent.
:type events: SendType
: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
:rtype: None
:raises: :class:`ValueError`, when events do not follow specified SendType.
"""
if not isinstance(events, list):
events = cast(ListEventType, [events])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,30 @@
]

class EventGridPublisherClient():
"""Asynchronous EventGrid Python Publisher Client.
"""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.
:type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential
:rtype: None

.. admonition:: Example:

.. literalinclude:: ../samples/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: 8
:caption: Creating the EventGridPublisherClient with an endpoint and AzureKeyCredential.

.. literalinclude:: ../samples/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: 8
:caption: Creating the EventGridPublisherClient with an endpoint and AzureSasCredential.
"""

def __init__(
Expand Down Expand Up @@ -101,18 +118,67 @@ async def send(
self,
events: SendType,
**kwargs: Any) -> None:
"""Sends event data to topic hostname specified during client initialization.
Multiple events can be published at once by seding a list of events. It is very
inefficient to loop the send method for each event instead of just using a list
and we highly recommend against it.
"""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: 8
: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: 8
:caption: Publishing a CloudEvent.

A dict representation of respective serialized models can be used to send CloudEvent(s) or
EventGridEvent(s) instead of 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: 8
:caption: Publishing an EventGridEvent 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: 8
:caption: Publishing a CloudEvent using a dict-like representation.

When publishing a Custom schema event(s), a 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: 8
:caption: Publishing a Custom Schema event.

**WARNING**: To send multiple events at once, a list of events must be used.
It is very inefficient to loop the send method for each event instead of just
using a list and we highly recommend against it.

:param events: A list of CloudEvent/EventGridEvent to be sent.
:param events: A single event or a list of dictionaries/CloudEvent/EventGridEvent to be sent.
:type events: SendType
: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
:rtype: None
:raises: :class:`ValueError`, when events do not follow specified SendType.
"""
if not isinstance(events, list):
events = cast(ListEventType, [events])
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE: sample_authentication_async.py
DESCRIPTION:
These samples demonstrate authenticating an EventGridPublisherClient.
USAGE:
python sample_authentication_async.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
"<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net".
3) EVENTGRID_SAS - The shared access signature that is to be used to authenticate the client.
"""
# [START client_auth_with_key_cred_async]
import os
from azure.eventgrid.aio import EventGridPublisherClient
from azure.core.credentials import AzureKeyCredential

topic_key = os.environ["EG_ACCESS_KEY"]
endpoint = os.environ["EG_TOPIC_HOSTNAME"]

credential = AzureKeyCredential(topic_key)
client = EventGridPublisherClient(endpoint, credential)
# [END client_auth_with_key_cred_async]

# [START client_auth_with_sas_cred_async]
import os
from azure.eventgrid.aio import EventGridPublisherClient
from azure.core.credentials import AzureSasCredential

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

credential = AzureSasCredential(signature)
client = EventGridPublisherClient(endpoint, credential)
# [END client_auth_with_sas_cred_async]
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ async def publish():
credential = AzureKeyCredential(topic_key)
client = EventGridPublisherClient(endpoint, credential)

# [START publish_cloud_event_dict_async]
async with client:
client.send([
{
Expand All @@ -41,6 +42,7 @@ async def publish():
"id": "randomclouduuid11"
}
])
# [END publish_cloud_event_dict_async]

if __name__ == '__main__':
loop = asyncio.get_event_loop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

async def publish_event():
# authenticate client
# [START publish_custon_schema_async]
credential = AzureKeyCredential(key)
client = EventGridPublisherClient(endpoint, credential)

Expand All @@ -41,21 +42,11 @@ async def publish_event():
"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)

async with client:
# publish list of events
client.send(event_list)
print("Batch of size {} published".format(len(event_list)))
time.sleep(randint(1, 5))

async with client:
# publish list of events
await client.send(custom_schema_event)

# [END publish_custon_schema_async]

if __name__ == '__main__':
loop = asyncio.get_event_loop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
async def publish():
credential = AzureKeyCredential(topic_key)
client = EventGridPublisherClient(endpoint, credential)

# [START publish_eg_event_dict_async]
event0 = {
"eventType": "Contoso.Items.ItemReceived",
"data": {
Expand All @@ -52,6 +54,7 @@ async def publish():

async with client:
await client.send([event0, event1])
# [END publish_eg_event_dict_async]

if __name__ == '__main__':
loop = asyncio.get_event_loop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
2) EG_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format
"<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net".
"""
# [START publish_eg_event_to_topic_async]
import os
import asyncio
from azure.eventgrid import EventGridEvent
Expand All @@ -37,6 +38,7 @@ async def publish():
data_version="2.0"
)
])
# [END publish_eg_event_to_topic_async]

if __name__ == '__main__':
loop = asyncio.get_event_loop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
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_async]
import os
import asyncio
from azure.eventgrid import CloudEvent
Expand All @@ -37,6 +38,7 @@ async def publish():
subject="Door1"
)
])
# [END publish_cloud_event_to_topic_async]

if __name__ == '__main__':
loop = asyncio.get_event_loop()
Expand Down
Loading