Skip to content

Commit cafa7c6

Browse files
Rakshith Bhyravabhotlayunhaoling
andauthored
EG - add samples to docstrings (Azure#16873)
* Add admonitions to docstrings * lint * sample fix * Apply suggestions from code review Co-authored-by: Adam Ling (MSFT) <adam_ling@outlook.com> * comments * dedent * link * dedent Co-authored-by: Adam Ling (MSFT) <adam_ling@outlook.com>
1 parent 68959f1 commit cafa7c6

17 files changed

+271
-45
lines changed

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_helpers.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@ def generate_sas(endpoint, shared_access_key, expiration_date_utc, **kwargs):
3030
:keyword str api_version: The API Version to include in the signature.
3131
If not provided, the default API version will be used.
3232
:rtype: str
33+
34+
.. admonition:: Example:
35+
36+
.. literalinclude:: ../samples/sync_samples/sample_generate_sas.py
37+
:start-after: [START generate_sas]
38+
:end-before: [END generate_sas]
39+
:language: python
40+
:dedent: 0
41+
:caption: Generate a shared access signature.
3342
"""
3443

3544
full_endpoint = _get_full_endpoint(endpoint)

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_publisher_client.py

Lines changed: 72 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,29 @@
5555

5656

5757
class EventGridPublisherClient(object):
58-
"""EventGrid Python Publisher Client.
58+
"""EventGridPublisherClient publishes events to an EventGrid topic or domain.
59+
It can be used to publish either an EventGridEvent, a CloudEvent or a Custom Schema.
5960
6061
:param str endpoint: The topic endpoint to send the events to.
6162
:param credential: The credential object used for authentication which
6263
implements SAS key authentication or SAS token authentication.
6364
:type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential
65+
66+
.. admonition:: Example:
67+
68+
.. literalinclude:: ../samples/sync_samples/sample_authentication.py
69+
:start-after: [START client_auth_with_key_cred]
70+
:end-before: [END client_auth_with_key_cred]
71+
:language: python
72+
:dedent: 0
73+
:caption: Creating the EventGridPublisherClient with an endpoint and AzureKeyCredential.
74+
75+
.. literalinclude:: ../samples/sync_samples/sample_authentication.py
76+
:start-after: [START client_auth_with_sas_cred]
77+
:end-before: [END client_auth_with_sas_cred]
78+
:language: python
79+
:dedent: 0
80+
:caption: Creating the EventGridPublisherClient with an endpoint and AzureSasCredential.
6481
"""
6582

6683
def __init__(self, endpoint, credential, **kwargs):
@@ -98,18 +115,66 @@ def _policies(credential, **kwargs):
98115
@distributed_trace
99116
def send(self, events, **kwargs):
100117
# type: (SendType, Any) -> None
101-
"""Sends event data to topic hostname specified during client initialization.
102-
Multiple events can be published at once by seding a list of events. It is very
103-
inefficient to loop the send method for each event instead of just using a list
104-
and we highly recommend against it.
118+
"""Sends events to a topic or a domain specified during the client initialization.
119+
120+
A single instance or a list of dictionaries, CloudEvents or EventGridEvents are accepted.
121+
122+
.. admonition:: Example:
123+
124+
.. literalinclude:: ../samples/sync_samples/sample_publish_eg_events_to_a_topic.py
125+
:start-after: [START publish_eg_event_to_topic]
126+
:end-before: [END publish_eg_event_to_topic]
127+
:language: python
128+
:dedent: 0
129+
:caption: Publishing an EventGridEvent.
130+
131+
.. literalinclude:: ../samples/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py
132+
:start-after: [START publish_cloud_event_to_topic]
133+
:end-before: [END publish_cloud_event_to_topic]
134+
:language: python
135+
:dedent: 0
136+
:caption: Publishing a CloudEvent.
137+
138+
Dict representation of respective serialized models is accepted as CloudEvent(s) or
139+
EventGridEvent(s) apart from the strongly typed objects.
140+
141+
.. admonition:: Example:
142+
143+
.. literalinclude:: ../samples/sync_samples/sample_publish_eg_event_using_dict.py
144+
:start-after: [START publish_eg_event_dict]
145+
:end-before: [END publish_eg_event_dict]
146+
:language: python
147+
:dedent: 0
148+
:caption: Publishing an EventGridEvent using a dict-like representation.
149+
150+
.. literalinclude:: ../samples/sync_samples/sample_publish_cloud_event_using_dict.py
151+
:start-after: [START publish_cloud_event_dict]
152+
:end-before: [END publish_cloud_event_dict]
153+
:language: python
154+
:dedent: 0
155+
:caption: Publishing a CloudEvent using a dict-like representation.
156+
157+
When publishing a Custom Schema Event(s), dict-like representation is accepted.
158+
Either a single dictionary or a list of dictionaries can be passed.
159+
160+
.. admonition:: Example:
161+
162+
.. literalinclude:: ../samples/sync_samples/sample_publish_custom_schema_to_a_topic.py
163+
:start-after: [START publish_custom_schema]
164+
:end-before: [END publish_custom_schema]
165+
:language: python
166+
:dedent: 0
167+
:caption: Publishing a Custom Schema event.
168+
169+
**WARNING**: To gain the best performance when sending multiple events at one time,
170+
it is highly recommended to send a list of events instead of iterating over and sending each event in a loop.
105171
106-
:param events: A list of CloudEvent/EventGridEvent to be sent.
172+
:param events: A single instance or a list of dictionaries/CloudEvent/EventGridEvent to be sent.
107173
:type events: SendType
108174
:keyword str content_type: The type of content to be used to send the events.
109175
Has default value "application/json; charset=utf-8" for EventGridEvents,
110176
with "cloudevents-batch+json" for CloudEvents
111177
:rtype: None
112-
:raises: :class:`ValueError`, when events do not follow specified SendType.
113178
"""
114179
if not isinstance(events, list):
115180
events = cast(ListEventType, [events])

sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_publisher_client_async.py

Lines changed: 72 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,30 @@
5151
]
5252

5353
class EventGridPublisherClient():
54-
"""Asynchronous EventGrid Python Publisher Client.
54+
"""Asynchronous EventGridPublisherClient publishes events to an EventGrid topic or domain.
55+
It can be used to publish either an EventGridEvent, a CloudEvent or a Custom Schema.
5556
5657
:param str endpoint: The topic endpoint to send the events to.
5758
:param credential: The credential object used for authentication which implements
5859
SAS key authentication or SAS token authentication.
5960
:type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential
6061
:rtype: None
62+
63+
.. admonition:: Example:
64+
65+
.. literalinclude:: ../samples/async_samples/sample_authentication_async.py
66+
:start-after: [START client_auth_with_key_cred_async]
67+
:end-before: [END client_auth_with_key_cred_async]
68+
:language: python
69+
:dedent: 0
70+
:caption: Creating the EventGridPublisherClient with an endpoint and AzureKeyCredential.
71+
72+
.. literalinclude:: ../samples/async_samples/sample_authentication_async.py
73+
:start-after: [START client_auth_with_sas_cred_async]
74+
:end-before: [END client_auth_with_sas_cred_async]
75+
:language: python
76+
:dedent: 0
77+
:caption: Creating the EventGridPublisherClient with an endpoint and AzureSasCredential.
6178
"""
6279

6380
def __init__(
@@ -101,18 +118,66 @@ async def send(
101118
self,
102119
events: SendType,
103120
**kwargs: Any) -> None:
104-
"""Sends event data to topic hostname specified during client initialization.
105-
Multiple events can be published at once by seding a list of events. It is very
106-
inefficient to loop the send method for each event instead of just using a list
107-
and we highly recommend against it.
121+
"""Sends events to a topic or a domain specified during the client initialization.
122+
123+
A single instance or a list of dictionaries, CloudEvents or EventGridEvents are accepted.
124+
125+
.. admonition:: Example:
126+
127+
.. literalinclude:: ../samples/async_samples/sample_publish_eg_events_to_a_topic_async.py
128+
:start-after: [START publish_eg_event_to_topic_async]
129+
:end-before: [END publish_eg_event_to_topic_async]
130+
:language: python
131+
:dedent: 0
132+
:caption: Publishing an EventGridEvent.
133+
134+
.. literalinclude:: ../samples/async_samples/sample_publish_events_using_cloud_events_1.0_schema_async.py
135+
:start-after: [START publish_cloud_event_to_topic_async]
136+
:end-before: [END publish_cloud_event_to_topic_async]
137+
:language: python
138+
:dedent: 0
139+
:caption: Publishing a CloudEvent.
140+
141+
Dict representation of respective serialized models is accepted as CloudEvent(s) or
142+
EventGridEvent(s) apart from the strongly typed objects.
143+
144+
.. admonition:: Example:
145+
146+
.. literalinclude:: ../samples/async_samples/sample_publish_eg_event_using_dict_async.py
147+
:start-after: [START publish_eg_event_dict_async]
148+
:end-before: [END publish_eg_event_dict_async]
149+
:language: python
150+
:dedent: 0
151+
:caption: Publishing an EventGridEvent using a dict-like representation.
152+
153+
.. literalinclude:: ../samples/async_samples/sample_publish_cloud_event_using_dict_async.py
154+
:start-after: [START publish_cloud_event_dict_async]
155+
:end-before: [END publish_cloud_event_dict_async]
156+
:language: python
157+
:dedent: 0
158+
:caption: Publishing a CloudEvent using a dict-like representation.
159+
160+
When publishing a Custom Schema Event(s), dict-like representation is accepted.
161+
Either a single dictionary or a list of dictionaries can be passed.
162+
163+
.. admonition:: Example:
164+
165+
.. literalinclude:: ../samples/async_samples/sample_publish_custom_schema_to_a_topic_async.py
166+
:start-after: [START publish_custom_schema_async]
167+
:end-before: [END publish_custom_schema_async]
168+
:language: python
169+
:dedent: 0
170+
:caption: Publishing a Custom Schema event.
171+
172+
**WARNING**: To gain the best performance when sending multiple events at one time,
173+
it is highly recommended to send a list of events instead of iterating over and sending each event in a loop.
108174
109-
:param events: A list of CloudEvent/EventGridEvent to be sent.
175+
:param events: A single instance or a list of dictionaries/CloudEvent/EventGridEvent to be sent.
110176
:type events: SendType
111177
:keyword str content_type: The type of content to be used to send the events.
112178
Has default value "application/json; charset=utf-8" for EventGridEvents,
113179
with "cloudevents-batch+json" for CloudEvents
114180
:rtype: None
115-
:raises: :class:`ValueError`, when events do not follow specified SendType.
116181
"""
117182
if not isinstance(events, list):
118183
events = cast(ListEventType, [events])

sdk/eventgrid/azure-eventgrid/samples/README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ These code samples show common champion scenario operations with the Azure Event
1515

1616
* Generate Shared Access Signature: [sample_generate_sas.py][python-eg-generate-sas]
1717

18+
* Authenticate the client: [sample_authentication.py][python-eg-auth]
19+
1820
* Publish events to a topic using SAS: [sample_publish_events_to_a_topic_using_sas_credential_async.py][python-eg-sample-send-using-sas]
1921
* Publish Event Grid Events to a topic: [sample_publish_eg_events_to_a_topic.py][python-eg-sample-eg-event]
2022
* Publish EventGrid Events to a domain topic: [sample_publish_eg_events_to_a_domain_topic.py][python-eg-sample-eg-event-to-domain]
@@ -30,6 +32,8 @@ To publish events, dict representation of the models could also be used as follo
3032
## Async samples
3133
These code samples show common champion scenario operations with the Azure Event Grid client library using the async client.
3234

35+
* Authenticate the client: [sample_authentication_async.py][python-eg-auth-async]
36+
3337
* Publish events to a topic using SAS: [sample_publish_events_to_a_topic_using_sas_credential_async.py][python-eg-sample-send-using-sas-async]
3438
* Publish EventGrid Events to a topic: [sample_publish_eg_events_to_a_topic_async.py][python-eg-sample-eg-event-async]
3539
* Publish EventGrid Events to a domain topic: [sample_publish_eg_events_to_a_domain_topic_async.py][python-eg-sample-eg-event-to-domain-async]
@@ -45,7 +49,7 @@ To publish events, dict representation of the models could also be used as follo
4549
* More samples related to the send scenario can be seen [here][python-eg-publish-samples].
4650
* To see more samples related to consuming a payload from different messaging services as a typed object, please visit [Consume Samples][python-eg-consume-samples]
4751

48-
52+
[python-eg-auth]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_authentication.py
4953
[python-eg-generate-sas]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_generate_sas.py
5054
[python-eg-sample-send-using-sas]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_to_a_topic_using_sas_credential.py
5155
[python-eg-sample-eg-event]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_topic.py
@@ -55,6 +59,7 @@ To publish events, dict representation of the models could also be used as follo
5559
[python-eg-sample-send-eg-as-dict]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_event_using_dict.py
5660
[python-eg-sample-send-cloudevent-as-dict]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cloud_event_using_dict.py
5761

62+
[python-eg-auth-async]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_authentication_async.py
5863
[python-eg-sample-send-using-sas-async]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_to_a_topic_using_sas_credential_async.py
5964
[python-eg-sample-eg-event-async]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_topic_async.py
6065
[python-eg-sample-eg-event-to-domain-async]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_domain_async.py
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# --------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See License.txt in the project root for
4+
# license information.
5+
# --------------------------------------------------------------------------
6+
"""
7+
FILE: sample_authentication_async.py
8+
DESCRIPTION:
9+
These samples demonstrate authenticating an EventGridPublisherClient.
10+
USAGE:
11+
python sample_authentication_async.py
12+
Set the environment variables with your own values before running the sample:
13+
1) EG_ACCESS_KEY - The access key of your eventgrid account.
14+
2) EG_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format
15+
"<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net".
16+
3) EVENTGRID_SAS - The shared access signature that is to be used to authenticate the client.
17+
"""
18+
# [START client_auth_with_key_cred_async]
19+
import os
20+
from azure.eventgrid.aio import EventGridPublisherClient
21+
from azure.core.credentials import AzureKeyCredential
22+
23+
topic_key = os.environ["EG_ACCESS_KEY"]
24+
endpoint = os.environ["EG_TOPIC_HOSTNAME"]
25+
26+
credential = AzureKeyCredential(topic_key)
27+
client = EventGridPublisherClient(endpoint, credential)
28+
# [END client_auth_with_key_cred_async]
29+
30+
# [START client_auth_with_sas_cred_async]
31+
import os
32+
from azure.eventgrid.aio import EventGridPublisherClient
33+
from azure.core.credentials import AzureSasCredential
34+
35+
signature = os.environ["EVENTGRID_SAS"]
36+
endpoint = os.environ["EG_TOPIC_HOSTNAME"]
37+
38+
credential = AzureSasCredential(signature)
39+
client = EventGridPublisherClient(endpoint, credential)
40+
# [END client_auth_with_sas_cred_async]

sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cloud_event_using_dict_async.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ async def publish():
2828
credential = AzureKeyCredential(topic_key)
2929
client = EventGridPublisherClient(endpoint, credential)
3030

31+
# [START publish_cloud_event_dict_async]
3132
async with client:
3233
client.send([
3334
{
@@ -41,6 +42,7 @@ async def publish():
4142
"id": "randomclouduuid11"
4243
}
4344
])
45+
# [END publish_cloud_event_dict_async]
4446

4547
if __name__ == '__main__':
4648
loop = asyncio.get_event_loop()

sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_custom_schema_to_a_topic_async.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
async def publish_event():
3232
# authenticate client
33+
# [START publish_custon_schema_async]
3334
credential = AzureKeyCredential(key)
3435
client = EventGridPublisherClient(endpoint, credential)
3536

@@ -41,21 +42,11 @@ async def publish_event():
4142
"customEventTime": dt.datetime.now(UTC()).isoformat(),
4243
"customData": "sample data"
4344
}
44-
45-
# publish events
46-
for _ in range(3):
47-
48-
event_list = [] # list of events to publish
49-
# create events and append to list
50-
for j in range(randint(1, 3)):
51-
event_list.append(custom_schema_event)
52-
53-
async with client:
54-
# publish list of events
55-
client.send(event_list)
56-
print("Batch of size {} published".format(len(event_list)))
57-
time.sleep(randint(1, 5))
58-
45+
async with client:
46+
# publish list of events
47+
await client.send(custom_schema_event)
48+
49+
# [END publish_custon_schema_async]
5950

6051
if __name__ == '__main__':
6152
loop = asyncio.get_event_loop()

sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_event_using_dict_async.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
async def publish():
3030
credential = AzureKeyCredential(topic_key)
3131
client = EventGridPublisherClient(endpoint, credential)
32+
33+
# [START publish_eg_event_dict_async]
3234
event0 = {
3335
"eventType": "Contoso.Items.ItemReceived",
3436
"data": {
@@ -52,6 +54,7 @@ async def publish():
5254

5355
async with client:
5456
await client.send([event0, event1])
57+
# [END publish_eg_event_dict_async]
5558

5659
if __name__ == '__main__':
5760
loop = asyncio.get_event_loop()

sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_topic_async.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
2) EG_TOPIC_HOSTNAME - The topic hostname. Typically it exists in the format
1515
"<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net".
1616
"""
17+
# [START publish_eg_event_to_topic_async]
1718
import os
1819
import asyncio
1920
from azure.eventgrid import EventGridEvent
@@ -37,6 +38,7 @@ async def publish():
3738
data_version="2.0"
3839
)
3940
])
41+
# [END publish_eg_event_to_topic_async]
4042

4143
if __name__ == '__main__':
4244
loop = asyncio.get_event_loop()

0 commit comments

Comments
 (0)