From cd8cf6ae5ae9343ba4b46147b5f6a489ca06e359 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 8 Apr 2024 13:35:05 -0700 Subject: [PATCH] [EG] Beta One Client (#34973) * [EG] dont hardcode api_version on request (#34965) * dont hardcode api_version on request * pylint fixes * revert * api version * Update sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_publisher_client_async.py * Update sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_publisher_client_async.py * add sync side patches * aio patches * update readme samples * all samples use EGClient * update readme samples * fix imports * import issue * missing pathc * allow sas cred * typo * updates * sas * client * self serialize cloudevent * add bakc in * updates * update ptach * update * update exception logic * async w client * aio [atch * typo * import * update links * tests * raise error * content type * use more fake url * remove content type * mypy * update apiversion * content type * unitttests * update auth * updates * add level * update readme * update * binary mode * args, kwargs * remove auth * add sample comments * testing * move around readme * content type * update tests * docstring * cncf event * add more tests * update doc * update inits to prevent typing errors * ran blakc * fix pylint patch * changes * add all kwargs * indent * reviews * nit * name changes * options * options/result rename * Revert "options" This reverts commit fe0623a51126ae474a8465ecc60ac5e6aadae5c3. * Revert "options/result rename" This reverts commit 6d374222f1fd763e197d280f43cb1a511a16a0c5. * fix tests * remove or None * remove EGPubClient * remove options naming * Revert "remove EGPubClient" This reverts commit bf943640407239ae568c81d7ee0558305c3e30f7. * typeerror * update readme * readme nit * readme updates * add send operation samples * add datacontenttpye * typo * make Options bag models kwargs * remove models * import * exception * update changelog * shorten operation names * nit --- sdk/eventgrid/azure-eventgrid/CHANGELOG.md | 9 +- sdk/eventgrid/azure-eventgrid/README.md | 324 +++--- .../azure-eventgrid/azure/__init__.py | 2 +- .../azure/eventgrid/__init__.py | 2 +- .../azure/eventgrid/_legacy/_helpers.py | 4 +- .../eventgrid/_legacy/_publisher_client.py | 20 +- .../_legacy/aio/_publisher_client_async.py | 12 +- .../azure/eventgrid/_operations/__init__.py | 2 +- .../eventgrid/_operations/_operations.py | 920 +++--------------- .../azure/eventgrid/_operations/_patch.py | 849 ++++++++++------ .../azure-eventgrid/azure/eventgrid/_patch.py | 85 +- .../azure/eventgrid/aio/__init__.py | 2 +- .../eventgrid/aio/_operations/__init__.py | 2 +- .../eventgrid/aio/_operations/_operations.py | 920 +++--------------- .../azure/eventgrid/aio/_operations/_patch.py | 547 +++++++---- .../azure/eventgrid/aio/_patch.py | 78 +- .../azure/eventgrid/models/__init__.py | 12 - .../azure/eventgrid/models/_models.py | 123 +-- .../azure/eventgrid/models/_patch.py | 23 +- .../azure-eventgrid/samples/README.md | 76 +- .../sample_acknowledge_operation_async.py | 21 +- .../sample_all_operations_async.py | 46 +- .../sample_binary_mode_async.py | 21 +- .../sample_publish_operation_async.py | 23 +- .../sample_publish_receive_renew_async.py | 24 +- .../sample_publish_release_receive_async.py | 35 +- .../sample_receive_operation_async.py | 17 +- .../sample_reject_operation_async.py | 21 +- .../sample_release_operation_async.py | 21 +- .../sample_renew_locks_operation_async.py | 21 +- .../sample_authentication_async.py | 12 +- ...le_publish_cloud_event_using_dict_async.py | 4 +- .../sample_publish_cncf_cloud_events_async.py | 29 +- ..._publish_custom_schema_to_a_topic_async.py | 4 +- ...ample_publish_eg_event_using_dict_async.py | 4 +- ...ple_publish_eg_events_to_a_domain_async.py | 42 +- ...mple_publish_eg_events_to_a_topic_async.py | 26 +- ...s_to_a_topic_using_sas_credential_async.py | 4 +- ...nts_using_cloud_events_1.0_schema_async.py | 26 +- .../sample_publish_to_channel_async.py | 4 +- ...ish_cloud_events_to_custom_topic_sample.py | 4 +- ...ish_cloud_events_to_domain_topic_sample.py | 4 +- ...sh_custom_schema_events_to_topic_sample.py | 4 +- ...vent_grid_events_to_custom_topic_sample.py | 4 +- ...ish_with_shared_access_signature_sample.py | 4 +- .../sample_aad_auth_operation.py | 14 - .../sample_acknowledge_operation.py | 21 +- .../sample_all_operations.py | 42 +- .../sample_binary_mode.py | 19 +- .../sample_eg_client_authentication.py | 27 - .../sample_publish_operation.py | 21 +- .../sample_publish_receive_renew.py | 28 +- .../sample_publish_release_receive.py | 35 +- .../sample_receive_operation.py | 17 +- .../sample_reject_operation.py | 21 +- .../sample_release_operation.py | 21 +- .../sample_renew_locks_operation.py | 21 +- .../sync_samples/sample_authentication.py | 22 +- .../sample_publish_cloud_event_using_dict.py | 4 +- .../sample_publish_cncf_cloud_events.py | 4 +- ...sample_publish_custom_schema_to_a_topic.py | 4 +- .../sample_publish_eg_event_using_dict.py | 4 +- .../sample_publish_eg_events_to_a_domain.py | 4 +- .../sample_publish_eg_events_to_a_topic.py | 4 +- ..._events_to_a_topic_using_sas_credential.py | 4 +- ...sh_events_using_cloud_events_1.0_schema.py | 4 +- .../sync_samples/sample_publish_to_channel.py | 4 +- .../azure-eventgrid/tests/conftest.py | 16 + .../azure-eventgrid/tests/test_dual_client.py | 287 ++++++ .../azure-eventgrid/tests/test_eg_client.py | 68 +- .../tests/test_eg_client_exceptions.py | 50 +- .../tests/unittests/test_binary_mode.py | 7 +- 72 files changed, 2540 insertions(+), 2670 deletions(-) delete mode 100644 sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py delete mode 100644 sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_eg_client_authentication.py create mode 100644 sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py diff --git a/sdk/eventgrid/azure-eventgrid/CHANGELOG.md b/sdk/eventgrid/azure-eventgrid/CHANGELOG.md index 6f725d30961c..7aa841fd57e0 100644 --- a/sdk/eventgrid/azure-eventgrid/CHANGELOG.md +++ b/sdk/eventgrid/azure-eventgrid/CHANGELOG.md @@ -4,11 +4,14 @@ ### Features Added -### Breaking Changes +- This is a Beta of the EventGridClient + - EventGridClient `send` can be used for both Event Grid Namespace Resources and Event Grid Basic Resources. + - Added a kwarg `level` in the EventGridClient constructor. The default value is `Standard` which creates a client for an Event Grid Namespace Resource. -### Bugs Fixed + ### Breaking Changes + - Removed the `AcknowledgeOptions`,`ReleaseOptions`, `RejectOptions`, and `RenewLockOptions` models. `lock_tokens` can now be specified as a `kwarg` on the operation. + - Renamed `publish_cloud_events` to `send`, `receive_cloud_events` to `receive`, `release_cloud_events` to `release`, `acknowledge_cloud_events` to `acknowledge`, `reject_cloud_events` to `reject`, and `renew_cloud_event_locks` to `renew_locks`. -### Other Changes ## 4.18.0 (2024-03-12) diff --git a/sdk/eventgrid/azure-eventgrid/README.md b/sdk/eventgrid/azure-eventgrid/README.md index 8602ece12129..9952c57507f8 100644 --- a/sdk/eventgrid/azure-eventgrid/README.md +++ b/sdk/eventgrid/azure-eventgrid/README.md @@ -2,7 +2,7 @@ Azure Event Grid is a fully-managed intelligent event routing service that allows for uniform event consumption using a publish-subscribe model. -[Source code][python-eg-src] +| [Source code][python-eg-src] | [Package (PyPI)][python-eg-pypi] | [Package (Conda)](https://anaconda.org/microsoft/azure-eventgrid/) | [API reference documentation][python-eg-ref-docs] @@ -12,14 +12,34 @@ Azure Event Grid is a fully-managed intelligent event routing service that allow ## _Disclaimer_ -This is a beta release of Azure EventGrid's `EventGridClient`, which along with the GA `EventGridPublisherClient`. `EventGridClient` supports `publish_cloud_events`, `receive_cloud_events`, `acknowledge_cloud_events` , `release_cloud_events`, `reject_cloud_events`, and `renew_cloud_event_locks` operations. Please refer to the [samples](https://github.com/Azure/azure-sdk-for-python/tree/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples) for further information. +This is a beta release of Azure EventGrid's `EventGridClient`. `EventGridClient` supports `send`, `receive`, `acknowledge` , `release`, `reject`, and `renew_locks` operations. Please refer to the [samples](https://github.com/Azure/azure-sdk-for-python/tree/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples) for further information. ## Getting started ### Prerequisites -* Python 3.7 or later is required to use this package. -* You must have an [Azure subscription][azure_subscription] and an Event Grid Topic resource to use this package. Follow this [step-by-step tutorial](https://docs.microsoft.com/azure/event-grid/custom-event-quickstart-portal) to register the Event Grid resource provider and create Event Grid topics using the [Azure portal](https://portal.azure.com/). There is a [similar tutorial](https://docs.microsoft.com/azure/event-grid/custom-event-quickstart) using [Azure CLI](https://docs.microsoft.com/cli/azure). - +* Python 3.8 or later is required to use this package. +* You must have an [Azure subscription][azure_subscription] and at least one of the following: + * an Event Grid Namespace resource. To create an Event Grid Namespace resource follow [this tutorial](https://learn.microsoft.com/azure/event-grid/create-view-manage-namespaces). + * an Event Grid Basic resource. To create an Event Grid Basic resource via the Azure portal follow this [step-by-step tutorial](https://docs.microsoft.com/azure/event-grid/custom-event-quickstart-portal). To create an Event Grid Basic resource via the [Azure CLI](https://docs.microsoft.com/cli/azure) follow this [tutorial](https://docs.microsoft.com/azure/event-grid/custom-event-quickstart) + +### Event Grid Resources + +Below is a brief synopsis of the differences between Azure Event Grid Namespaces and Azure Event Grid Basic. +More information on the two resource types can be found [here](https://learn.microsoft.com/azure/event-grid/choose-right-tier). + +| Feature | Namespaces (Standard) | Basic | +| :---------------- | :------: | :----: | +| Throughput | High | Low | +| MQTT | Yes | No | +| Publish and Subscribe to custom events | Yes | Yes | +| Push Delivery to Event Hubs | Yes | Yes | +| Maximum message retention | 7 days | 1 day | +| Push Delivery to Azure Services | No | Yes | +| Subscribe to Azure System Events | No | Yes | +| Subscribe to Partner Events | No | Yes | +| Domain Scope Subscriptions | No | Yes | + +**Note:** Azure Event Grid Namespaces only supports the Cloud Event v1.0 Schema. ### Install the package Install the Azure Event Grid client library for Python with [pip][pip]: @@ -28,17 +48,29 @@ Install the Azure Event Grid client library for Python with [pip][pip]: pip install azure-eventgrid ``` -* An existing Event Grid topic or domain is required. You can create the resource using [Azure Portal][azure_portal_create_EG_resource] or [Azure CLI][azure_cli_link] +* An existing Event Grid Basic topic or domain, or Event Grid Namespace topic is required. You can create the resource using [Azure Portal][azure_portal_create_EG_resource] or [Azure CLI][azure_cli_link] If you use Azure CLI, replace `` and `` with your own unique names. -#### Create an Event Grid Topic +#### Create an Event Grid Namespace + +``` +az eventgrid namespace create --location --resource-group --name +``` + +#### Create an Event Grid Namespace Topic + +``` +az eventgrid namespace create topic --location --resource-group --name +``` + +#### Create an Event Grid Basic Topic ``` az eventgrid topic --create --location --resource-group --name ``` -#### Create an Event Grid Domain +#### Create an Event Grid Basic Domain ``` az eventgrid domain --create --location --resource-group --name @@ -47,6 +79,11 @@ az eventgrid domain --create --location --resource-group -#### Looking up the endpoint +### Looking up the endpoint + +#### Event Grid Namespace +You can find the Namespace endpoint within the Event Grid Namespace resource on the Azure portal. This will look like: +`"..eventgrid.azure.net"` + +#### Event Grid Basic You can find the topic endpoint within the Event Grid Topic resource on the Azure portal. This will look like: `"https://..eventgrid.azure.net/api/events"` -#### Create the client with AzureKeyCredential +### Create the client with AzureKeyCredential To use an Access key as the `credential` parameter, pass the key as a string into an instance of [AzureKeyCredential][azure-key-credential]. @@ -86,49 +129,68 @@ pass the key as a string into an instance of [AzureKeyCredential][azure-key-cred ```python import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient from azure.core.credentials import AzureKeyCredential -topic_key = os.environ["EVENTGRID_TOPIC_KEY"] -endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] +key = os.environ["EVENTGRID_KEY"] +endpoint = os.environ["EVENTGRID_ENDPOINT"] -credential_key = AzureKeyCredential(topic_key) -client = EventGridPublisherClient(endpoint, credential_key) +credential_key = AzureKeyCredential(key) +client = EventGridClient(endpoint, credential_key) ``` -> **Note:** A client may also be authenticated via SAS signature, using the `AzureSasCredential`. A sample demonstrating this, is available [here][python-eg-sample-send-using-sas] ([async_version][python-eg-sample-send-using-sas-async]). +> **Note:** A Basic client may also be authenticated via SAS signature, using the `AzureSasCredential`. A sample demonstrating this, is available [here][python-eg-sample-send-using-sas] ([async_version][python-eg-sample-send-using-sas-async]). > **Note:** The `generate_sas` method can be used to generate a shared access signature. A sample demonstrating this can be seen [here][python-eg-generate-sas]. ## Key concepts -### Topic +### *Event Grid Namespace* + +A **[namespace](https://learn.microsoft.com/azure/event-grid/concepts-event-grid-namespaces#namespaces)** is a management container for other resources. It allows for grouping of related resources in order to manage them under one subscription. + +#### Namespace Topic + +A **[namespace topic](https://learn.microsoft.com/azure/event-grid/concepts-event-grid-namespaces#namespace-topics)** is a topic that is created within an Event Grid namespace. The client publishes events to an HTTP namespace endpoint specifying a namespace topic where published events are logically contained. A namespace topic only supports the CloudEvent v1.0 schema. + +#### Event Subscription + +An **[event subscription](https://learn.microsoft.com/azure/event-grid/concepts-event-grid-namespaces#event-subscriptions)** is a configuration resource associated with a single topic. + +#### Binary Content Mode + +A namespace topic can receive CloudEvents published in **[binary mode](https://learn.microsoft.com/azure/event-grid/concepts-event-grid-namespaces#binary-content-mode)**. + +### *Event Grid Basic* + +#### Topic A **[topic](https://docs.microsoft.com/azure/event-grid/concepts#topics)** is a channel within the EventGrid service to send events. The event schema that a topic accepts is decided at topic creation time. If events of a schema type are sent to a topic that requires a different schema type, errors will be raised. -### Domain +#### Domain An event **[domain](https://docs.microsoft.com/azure/event-grid/event-domains)** is a management tool for large numbers of Event Grid topics related to the same application. They allow you to publish events to thousands of topics. Domains also give you authorization and authentication control over each topic. For more information, visit [Event domain overview](https://docs.microsoft.com/azure/event-grid/event-domains). -When you create an event domain, a publishing endpoint for this domain is made available to you. This process is similar to creating an Event Grid Topic. The only difference is that, when publishing to a domain, you must specify the topic within the domain that you'd like the event to be delivered to. - -### Event schemas +#### Event schemas An **[event](https://docs.microsoft.com/azure/event-grid/concepts#events)** is the smallest amount of information that fully describes something that happened in the system. When a custom topic or domain is created, you must specify the schema that will be used when publishing events. Event Grid supports multiple schemas for encoding events. -#### Event Grid schema -While you may configure your topic to use a [custom schema](https://docs.microsoft.com/azure/event-grid/input-mappings), it is more common to use the already-defined Event Grid schema. See the specifications and requirements [here](https://docs.microsoft.com/azure/event-grid/event-schema). +##### System Topics +A **[system topic](https://docs.microsoft.com/azure/event-grid/system-topics)** in Event Grid represents one or more events published by Azure services such as Azure Storage or Azure Event Hubs. For example, a system topic may represent all blob events or only blob creation and blob deletion events published for a specific storage account. -#### CloudEvents v1.0 schema -Another option is to use the CloudEvents v1.0 schema. [CloudEvents](https://cloudevents.io/) is a Cloud Native Computing Foundation project which produces a specification for describing event data in a common way. The service summary of CloudEvents can be found [here](https://docs.microsoft.com/azure/event-grid/cloud-event-schema). +The names of the various event types for the system events published to Azure Event Grid are available in `azure.eventgrid.SystemEventNames`. +For complete list of recognizable system topics, visit [System Topics](https://docs.microsoft.com/azure/event-grid/system-topics). + + For more information about the key concepts on Event Grid, see [Concepts in Azure Event Grid][publisher-service-doc]. + +## EventGridClient -### EventGridPublisherClient -`EventGridPublisherClient` provides operations to send event data to a topic hostname specified during client initialization. +`EventGridClient` provides operations to send to, receive from, acknowledge, reject, release event data for a resource specified during client initialization. -Regardless of the schema that your topic or domain is configured to use, `EventGridPublisherClient` will be used to publish events to it. Use the `send` method publishing events. +If you are using Event Grid Basic, regardless of the schema that your topic or domain is configured to use, `EventGridClient` will be used to publish events to it. Use the `send` method to publish events. -The following formats of events are allowed to be sent: +The following formats of events are allowed to be sent to an EventGrid Basic resource: - A list or a single instance of strongly typed EventGridEvents. - A dict representation of a serialized EventGridEvent object. - A list or a single instance of strongly typed CloudEvents. @@ -136,18 +198,13 @@ The following formats of events are allowed to be sent: - A dict representation of any Custom Schema. -Please have a look at the [samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/eventgrid/azure-eventgrid/samples) for detailed examples. - +The following formats of events are allowed to be sent to an EventGrid Namespace resource: - **Note:** It is important to know if your topic supports CloudEvents or EventGridEvents before publishing. If you send to a topic that does not support the schema of the event you are sending, send() will throw an exception. +* A list of single instance of strongly typed CloudEvents. +* A dict representation of a serialized CloudEvent object. -### System Topics -A **[system topic](https://docs.microsoft.com/azure/event-grid/system-topics)** in Event Grid represents one or more events published by Azure services such as Azure Storage or Azure Event Hubs. For example, a system topic may represent all blob events or only blob creation and blob deletion events published for a specific storage account. - -The names of the various event types for the system events published to Azure Event Grid are available in `azure.eventgrid.SystemEventNames`. -For complete list of recognizable system topics, visit [System Topics](https://docs.microsoft.com/azure/event-grid/system-topics). +Please have a look at the [samples](https://github.com/Azure/azure-sdk-for-python/tree/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples) for detailed examples. - For more information about the key concepts on Event Grid, see [Concepts in Azure Event Grid][publisher-service-doc]. ## Event Grid on Kubernetes with Azure Arc @@ -174,34 +231,10 @@ The following sections provide several code snippets covering some of the most c * [Send a Cloud Event](#send-a-cloud-event) * [Send Multiple Events](#send-multiple-events) * [Send events as Dictionaries](#send-events-as-dictionaries) +* [Receive events](#receive-events-from-namespace) * [Consume a payload from storage queue](#consume-from-storage-queue) * [Consume from ServiceBus](#consume-from-servicebus) -### Send an Event Grid Event - -This example publishes an Event Grid event. - -```python -import os -from azure.core.credentials import AzureKeyCredential -from azure.eventgrid import EventGridPublisherClient, EventGridEvent - -key = os.environ["EG_ACCESS_KEY"] -endpoint = os.environ["EG_TOPIC_HOSTNAME"] - -event = EventGridEvent( - data={"team": "azure-sdk"}, - subject="Door1", - event_type="Azure.Sdk.Demo", - data_version="2.0" -) - -credential = AzureKeyCredential(key) -client = EventGridPublisherClient(endpoint, credential) - -client.send(event) -``` - ### Send a Cloud Event This example publishes a Cloud event. @@ -210,10 +243,12 @@ This example publishes a Cloud event. import os from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient, ClientLevel + +key = os.environ["EVENTGRID_NAMESPACE_KEY"] +endpoint = os.environ["EVENTGRID_NAMESPACE_ENDPOINT"] +topic_name = os.environ["EVENTGRID_TOPIC_NAME"] -key = os.environ["CLOUD_ACCESS_KEY"] -endpoint = os.environ["CLOUD_TOPIC_HOSTNAME"] event = CloudEvent( type="Azure.Sdk.Sample", @@ -222,9 +257,9 @@ event = CloudEvent( ) credential = AzureKeyCredential(key) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level=ClientLevel.STANDARD) -client.send(event) +client.send(topic_name, event) ``` ### Send Multiple events @@ -237,10 +272,11 @@ It is possible to send events as a batch when sending multiple events to a topic import os from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient, ClientLevel -key = os.environ["CLOUD_ACCESS_KEY"] -endpoint = os.environ["CLOUD_TOPIC_HOSTNAME"] +key = os.environ["EVENTGRID_NAMESPACE_KEY"] +endpoint = os.environ["EVENTGRID_NAMESPACE_ENDPOINT"] +topic_name = os.environ["EVENTGRID_TOPIC_NAME"] event0 = CloudEvent( type="Azure.Sdk.Sample", @@ -256,86 +292,88 @@ event1 = CloudEvent( events = [event0, event1] credential = AzureKeyCredential(key) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level=ClientLevel.STANDARD) -client.send(events) +client.send(topic_name, events) ``` -### Send events as dictionaries - -A dict representation of respective serialized models can also be used to publish CloudEvent(s) or EventGridEvent(s) apart from the strongly typed objects. +### Receive and Process Events from Namespace -Use a dict-like representation to send to a topic with custom schema as shown below. +Use EventGridClient's receive function to receive CloudEvents from a Namespace event subscription. Then try to acknowledge, reject, release or renew the locks. ```python import os import uuid import datetime as dt -from msrest.serialization import UTC from azure.core.credentials import AzureKeyCredential -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient, ClientLevel -key = os.environ["CUSTOM_SCHEMA_ACCESS_KEY"] -endpoint = os.environ["CUSTOM_SCHEMA_TOPIC_HOSTNAME"] - -event = custom_schema_event = { - "customSubject": "sample", - "customEventType": "sample.event", - "customDataVersion": "2.0", - "customId": uuid.uuid4(), - "customEventTime": dt.datetime.now(UTC()).isoformat(), - "customData": "sample data" - } +key = os.environ["EVENTGRID_KEY"] +endpoint = os.environ["EVENTGRID_ENDPOINT"] +topic_name = os.environ["EVENTGRID_TOPIC_NAME"] +sub_name = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] credential = AzureKeyCredential(key) -client = EventGridPublisherClient(endpoint, credential) - -client.send(event) -``` - -### Consume from storage queue - -This example consumes a message received from storage queue and deserializes it to a CloudEvent object. - -```python -from azure.core.messaging import CloudEvent -from azure.storage.queue import QueueServiceClient, BinaryBase64DecodePolicy -import os -import json +client = EventGridClient(endpoint, credential, level=ClientLevel.STANDARD) + +events = client.receive(topic_name, sub_name, max_events=4) + +for e in events: + renew_tokens = e.broker_properties.lock_token + renew_result = client.renew_locks( + topic_name=TOPIC_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=renew_tokens, + ) + +release_tokens = events[0].broker_properties.lock_token +release_result = client.release( + topic_name=TOPIC_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=release_tokens, +) -# all types of CloudEvents below produce same DeserializedEvent -connection_str = os.environ['STORAGE_QUEUE_CONN_STR'] -queue_name = os.environ['STORAGE_QUEUE_NAME'] +ack_tokens = events[1].broker_properties.lock_token +ack_result = client.acknowledge( + topic_name=TOPIC_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=ack_tokens, +) -with QueueServiceClient.from_connection_string(connection_str) as qsc: - payload = qsc.get_queue_client( - queue=queue_name, - message_decode_policy=BinaryBase64DecodePolicy() - ).peek_messages() +reject_tokens = events[2].broker_properties.lock_token +reject_result = client.reject( + topic_name=TOPIC_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=reject_tokens, +) - ## deserialize payload into a list of typed Events - events = [CloudEvent.from_dict(json.loads(msg.content)) for msg in payload] ``` -### Consume from servicebus +### Legacy EventGrid operations +#### Send an Event Grid Event + -This example consumes a payload message received from ServiceBus and deserializes it to an EventGridEvent object. +This example publishes an Event Grid event. ```python -from azure.eventgrid import EventGridEvent -from azure.servicebus import ServiceBusClient import os -import json +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid import EventGridClient, EventGridEvent, ClientLevel + +key = os.environ["EG_ACCESS_KEY"] +endpoint = os.environ["EG_TOPIC_HOSTNAME"] -# all types of EventGridEvents below produce same DeserializedEvent -connection_str = os.environ['SERVICE_BUS_CONN_STR'] -queue_name = os.environ['SERVICE_BUS_QUEUE_NAME'] +event = EventGridEvent( + data={"team": "azure-sdk"}, + subject="Door1", + event_type="Azure.Sdk.Demo", + data_version="2.0" +) -with ServiceBusClient.from_connection_string(connection_str) as sb_client: - payload = sb_client.get_queue_receiver(queue_name).receive_messages() +credential = AzureKeyCredential(key) +client = EventGridClient(endpoint, credential, level=ClientLevel.BASIC) - ## deserialize payload into a list of typed Events - events = [EventGridEvent.from_dict(json.loads(next(msg.body).decode('utf-8'))) for msg in payload] +client.send(event) ``` ## Distributed Tracing with EventGrid @@ -372,11 +410,11 @@ trace.get_tracer_provider().add_span_processor( ) ``` -Once the `tracer` and `exporter` are set, please follow the example below to start collecting traces while using the `send` method from the `EventGridPublisherClient` to send a CloudEvent object. +Once the `tracer` and `exporter` are set, please follow the example below to start collecting traces while using the `send` method from the `EventGridClient` to send a CloudEvent object. ```python import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient, ClientLevel from azure.core.messaging import CloudEvent from azure.core.credentials import AzureKeyCredential @@ -388,7 +426,7 @@ cloud_event = CloudEvent( data = {'test': 'hello'}, ) with tracer.start_as_current_span(name="MyApplication"): - client = EventGridPublisherClient(hostname, key) + client = EventGridClient(hostname, key, level=ClientLevel.BASIC) client.send(cloud_event) ``` @@ -419,6 +457,14 @@ The following section provides several code snippets illustrating common pattern These code samples show common champion scenario operations with the Azure Event Grid client library. +#### Namespaces EventGrid Scenarios + +* Authenticate the client: [sample_eg_client_authentication.py][python-eg-client-auth-samples] +* Sample of all operations: [sample_all_operations.py][python-eg-client-all-ops-sample] +* Publish cloud event in binary mode: [sample_binary_mode_operation.py][python-eg-client-binary-mode-sample] + +#### Basic EventGrid Scenarios + * Generate Shared Access Signature: [sample_generate_sas.py][python-eg-generate-sas] * Authenticate the client: [sample_authentication.py][python-eg-auth] ([async_version][python-eg-auth-async]) @@ -455,7 +501,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [azure_cli_link]: https://pypi.org/project/azure-cli/ -[python-eg-src]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/ +[python-eg-src]: https://github.com/Azure/azure-sdk-for-python/tree/feature/eventgrid/sdk/eventgrid/azure-eventgrid [python-eg-pypi]: https://pypi.org/project/azure-eventgrid [python-eg-product-docs]: https://docs.microsoft.com/azure/event-grid/overview [python-eg-ref-docs]: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-eventgrid/latest/index.html @@ -494,7 +540,17 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [python-eg-consume-samples]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/consume_samples [python-eg-sample-consume-custom-payload]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_consume_custom_payload.py + +[python-eg-client-aad-auth-samples]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py + +[python-eg-client-auth-samples]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_eg_client_authentication.py + +[python-eg-client-all-ops-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py + +[python-eg-client-binary-mode-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py + + [cla]: https://cla.microsoft.com [code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -[coc_contact]: mailto:opencode@microsoft.com +[coc_contact]: mailto:opencode@microsoft.com \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/azure/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/__init__.py index 5960c353a898..0d1f7edf5dc6 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore \ No newline at end of file +__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py index 32166aad43a3..f6da3df3d6bc 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._client import EventGridClient +from ._patch import EventGridClient from ._version import VERSION __version__ = VERSION diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py index fbc84fe522b1..0e7f08461e26 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_helpers.py @@ -172,7 +172,7 @@ def _from_cncf_events(event): # pylint: disable=inconsistent-return-statements raise ValueError(msg) from err -def _build_request(endpoint, content_type, events, *, channel_name=None): +def _build_request(endpoint, content_type, events, *, channel_name=None, api_version=constants.DEFAULT_API_VERSION): serialize = Serializer() header_parameters: Dict[str, Any] = {} header_parameters['Content-Type'] = serialize.header("content_type", content_type, 'str') @@ -181,7 +181,7 @@ def _build_request(endpoint, content_type, events, *, channel_name=None): header_parameters["aeg-channel-name"] = channel_name query_parameters: Dict[str, Any] = {} - query_parameters['api-version'] = serialize.query("api_version", "2018-01-01", 'str') + query_parameters['api-version'] = serialize.query("api_version", api_version, 'str') body = serialize.body(events, "[object]") if body is None: diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py index 695ad7e9c42e..409644f893dc 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/_publisher_client.py @@ -44,6 +44,7 @@ EventGridPublisherClient as EventGridPublisherClientImpl, ) from ._policies import CloudEventDistributedTracingPolicy +from ._constants import DEFAULT_API_VERSION from ._version import VERSION if TYPE_CHECKING: @@ -81,6 +82,9 @@ class EventGridPublisherClient( implements SAS key authentication or SAS token authentication or a TokenCredential. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or ~azure.core.credentials.TokenCredential + :keyword api_version: Api Version. Will default to the most recent Api Version. Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str :rtype: None .. admonition:: Example: @@ -100,12 +104,19 @@ class EventGridPublisherClient( :caption: Creating the EventGridPublisherClient with an endpoint and AzureSasCredential. """ - def __init__(self, endpoint, credential, **kwargs): - # type: (str, Union[AzureKeyCredential, AzureSasCredential, TokenCredential], Any) -> None + def __init__( + self, + endpoint: str, + credential: Union["AzureKeyCredential", "AzureSasCredential", "TokenCredential"], + *, + api_version: Optional[str] = None, + **kwargs: Any + ) -> None: self._endpoint = endpoint self._client = EventGridPublisherClientImpl( policies=EventGridPublisherClient._policies(credential, **kwargs), **kwargs ) + self._api_version = api_version if api_version is not None else DEFAULT_API_VERSION @staticmethod def _policies(credential, **kwargs): @@ -217,9 +228,8 @@ def send( _eventgrid_data_typecheck(event) response = self._client.send_request( # pylint: disable=protected-access _build_request( - self._endpoint, content_type, events, channel_name=channel_name - ), - **kwargs + self._endpoint,content_type, events, channel_name=channel_name, api_version=self._api_version), + **kwargs ) error_map = { 401: ClientAuthenticationError, diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py index b57d9dee8c0b..692451987fd7 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_legacy/aio/_publisher_client_async.py @@ -42,6 +42,7 @@ _get_authentication_policy, _from_cncf_events, ) +from .._constants import DEFAULT_API_VERSION from .._generated.aio import EventGridPublisherClient as EventGridPublisherClientAsync from .._version import VERSION @@ -73,6 +74,9 @@ class EventGridPublisherClient: # pylint: disable=client-accepts-api-version-ke SAS key authentication or SAS token authentication or an AsyncTokenCredential. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: Api Version. Will default to the most recent Api Version. Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str :rtype: None .. admonition:: Example: @@ -98,12 +102,15 @@ def __init__( credential: Union[ "AsyncTokenCredential", AzureKeyCredential, AzureSasCredential ], + *, + api_version: Optional[str] = None, **kwargs: Any ) -> None: self._client = EventGridPublisherClientAsync( policies=EventGridPublisherClient._policies(credential, **kwargs), **kwargs ) self._endpoint = endpoint + self._api_version = api_version if api_version is not None else DEFAULT_API_VERSION @staticmethod def _policies( @@ -220,9 +227,8 @@ async def send( for event in events: _eventgrid_data_typecheck(event) response = await self._client.send_request( # pylint: disable=protected-access - _build_request( - self._endpoint, content_type, events, channel_name=channel_name - ), + _build_request(self._endpoint, content_type, events, + channel_name=channel_name, api_version=self._api_version), **kwargs ) error_map = { diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py index c166e5de9c64..5d63b0e4eaa0 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._operations import EventGridClientOperationsMixin +from ._patch import EventGridClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py index b38ab06a9492..a2706730432d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py @@ -649,75 +649,18 @@ def _receive_cloud_events( # pylint: disable=protected-access @overload - def acknowledge_cloud_events( + def _acknowledge_cloud_events( # pylint: disable=protected-access self, topic_name: str, event_subscription_name: str, - acknowledge_options: _models.AcknowledgeOptions, + acknowledge_options: _models._models.AcknowledgeOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - acknowledged lockTokens, along with other failed lockTokens with their corresponding error - information. Successfully acknowledged events will no longer be available to any consumer. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param acknowledge_options: AcknowledgeOptions. Required. - :type acknowledge_options: ~azure.eventgrid.models.AcknowledgeOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.AcknowledgeResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - acknowledge_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. - ] - } - """ - + ... @overload - def acknowledge_cloud_events( + def _acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -726,59 +669,9 @@ def acknowledge_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - acknowledged lockTokens, along with other failed lockTokens with their corresponding error - information. Successfully acknowledged events will no longer be available to any consumer. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param acknowledge_options: AcknowledgeOptions. Required. - :type acknowledge_options: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.AcknowledgeResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. - ] - } - """ - + ... @overload - def acknowledge_cloud_events( + def _acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -787,64 +680,14 @@ def acknowledge_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - acknowledged lockTokens, along with other failed lockTokens with their corresponding error - information. Successfully acknowledged events will no longer be available to any consumer. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param acknowledge_options: AcknowledgeOptions. Required. - :type acknowledge_options: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.AcknowledgeResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. - ] - } - """ - + ... @distributed_trace - def acknowledge_cloud_events( + def _acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - acknowledge_options: Union[_models.AcknowledgeOptions, JSON, IO[bytes]], + acknowledge_options: Union[_models._models.AcknowledgeOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.AcknowledgeResult: """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the @@ -966,19 +809,64 @@ def acknowledge_cloud_events( + @overload + @api_version_validation( + params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + ) # pylint: disable=protected-access + def _release_cloud_events( # pylint: disable=protected-access + self, + topic_name: str, + event_subscription_name: str, + release_options: _models._models.ReleaseOptions, + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ReleaseResult: + ... + @overload + @api_version_validation( + params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + ) + def _release_cloud_events( + self, + topic_name: str, + event_subscription_name: str, + release_options: JSON, + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ReleaseResult: + ... @overload @api_version_validation( params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, ) - def release_cloud_events( + def _release_cloud_events( self, topic_name: str, event_subscription_name: str, - release_options: _models.ReleaseOptions, + release_options: IO[bytes], *, release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any + ) -> _models.ReleaseResult: + ... + + @distributed_trace + @api_version_validation( + params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + ) + def _release_cloud_events( + self, + topic_name: str, + event_subscription_name: str, + release_options: Union[_models._models.ReleaseOptions, JSON, IO[bytes]], + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + **kwargs: Any ) -> _models.ReleaseResult: """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request is successfully accepted. The response body will include the set of successfully released @@ -988,14 +876,12 @@ def release_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param release_options: ReleaseOptions. Required. - :type release_options: ~azure.eventgrid.models.ReleaseOptions + :param release_options: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, + IO[bytes] Required. + :type release_options: ~azure.eventgrid.models.ReleaseOptions or JSON or IO[bytes] :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. Known values are: 0, 10, 60, 600, and 3600. Default value is None. :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping :rtype: ~azure.eventgrid.models.ReleaseResult :raises ~azure.core.exceptions.HttpResponseError: @@ -1039,346 +925,84 @@ def release_cloud_events( ] } """ + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + } + error_map.update(kwargs.pop('error_map', {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + cls: ClsType[_models.ReleaseResult] = kwargs.pop( + 'cls', None + ) + + content_type = content_type or "application/json" + _content = None + if isinstance(release_options, (IOBase, bytes)): + _content = release_options + else: + _content = json.dumps(release_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_event_grid_release_cloud_events_request( + topic_name=topic_name, + event_subscription_name=event_subscription_name, + release_delay_in_seconds=release_delay_in_seconds, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, + stream=_stream, + **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models.ReleaseResult, + response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload - @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, - ) - def release_cloud_events( + def _reject_cloud_events( # pylint: disable=protected-access self, topic_name: str, event_subscription_name: str, - release_options: JSON, + reject_options: _models._models.RejectOptions, *, - release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully released - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param release_options: ReleaseOptions. Required. - :type release_options: JSON - :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. - Known values are: 0, 10, 60, 600, and 3600. Default value is None. - :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.ReleaseResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. - ] - } - """ - - @overload - @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, - ) - def release_cloud_events( - self, - topic_name: str, - event_subscription_name: str, - release_options: IO[bytes], - *, - release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully released - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param release_options: ReleaseOptions. Required. - :type release_options: IO[bytes] - :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. - Known values are: 0, 10, 60, 600, and 3600. Default value is None. - :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.ReleaseResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. - ] - } - """ - - - @distributed_trace - @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, - ) - def release_cloud_events( - self, - topic_name: str, - event_subscription_name: str, - release_options: Union[_models.ReleaseOptions, JSON, IO[bytes]], - *, - release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, - **kwargs: Any - ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully released - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param release_options: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, - IO[bytes] Required. - :type release_options: ~azure.eventgrid.models.ReleaseOptions or JSON or IO[bytes] - :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. - Known values are: 0, 10, 60, 600, and 3600. Default value is None. - :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.ReleaseResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - release_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. - ] - } - """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError - } - error_map.update(kwargs.pop('error_map', {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) - cls: ClsType[_models.ReleaseResult] = kwargs.pop( - 'cls', None - ) - - content_type = content_type or "application/json" - _content = None - if isinstance(release_options, (IOBase, bytes)): - _content = release_options - else: - _content = json.dumps(release_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_event_grid_release_cloud_events_request( - topic_name=topic_name, - event_subscription_name=event_subscription_name, - release_delay_in_seconds=release_delay_in_seconds, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize( - _models.ReleaseResult, - response.json() - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - - - @overload - def reject_cloud_events( - self, - topic_name: str, - event_subscription_name: str, - reject_options: _models.RejectOptions, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RejectResult: - """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully rejected - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param reject_options: RejectOptions. Required. - :type reject_options: ~azure.eventgrid.models.RejectOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RejectResult. The RejectResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.RejectResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - reject_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. - ] - } - """ - + ) -> _models.RejectResult: + ... @overload - def reject_cloud_events( + def _reject_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -1387,58 +1011,9 @@ def reject_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully rejected - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param reject_options: RejectOptions. Required. - :type reject_options: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RejectResult. The RejectResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.RejectResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. - ] - } - """ - + ... @overload - def reject_cloud_events( + def _reject_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -1447,63 +1022,14 @@ def reject_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully rejected - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param reject_options: RejectOptions. Required. - :type reject_options: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: RejectResult. The RejectResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.RejectResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. - ] - } - """ - + ... @distributed_trace - def reject_cloud_events( + def _reject_cloud_events( self, topic_name: str, event_subscription_name: str, - reject_options: Union[_models.RejectOptions, JSON, IO[bytes]], + reject_options: Union[_models._models.RejectOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.RejectResult: """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request @@ -1627,80 +1153,22 @@ def reject_cloud_events( @overload @api_version_validation( method_added_on="2023-10-01-preview", - ) - def renew_cloud_event_locks( + ) # pylint: disable=protected-access + def _renew_cloud_event_locks( # pylint: disable=protected-access self, topic_name: str, event_subscription_name: str, - renew_lock_options: _models.RenewLockOptions, + renew_lock_options: _models._models.RenewLockOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RenewCloudEventLocksResult: - """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - renewed lockTokens, along with other failed lockTokens with their corresponding error - information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param renew_lock_options: RenewLockOptions. Required. - :type renew_lock_options: ~azure.eventgrid.models.RenewLockOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with - MutableMapping - :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - renew_lock_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. - ] - } - """ - + ... @overload @api_version_validation( method_added_on="2023-10-01-preview", ) - def renew_cloud_event_locks( + def _renew_cloud_event_locks( self, topic_name: str, event_subscription_name: str, @@ -1709,63 +1177,12 @@ def renew_cloud_event_locks( content_type: str = "application/json", **kwargs: Any ) -> _models.RenewCloudEventLocksResult: - """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - renewed lockTokens, along with other failed lockTokens with their corresponding error - information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param renew_lock_options: RenewLockOptions. Required. - :type renew_lock_options: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with - MutableMapping - :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. - ] - } - """ - + ... @overload @api_version_validation( method_added_on="2023-10-01-preview", ) - def renew_cloud_event_locks( + def _renew_cloud_event_locks( self, topic_name: str, event_subscription_name: str, @@ -1774,68 +1191,17 @@ def renew_cloud_event_locks( content_type: str = "application/json", **kwargs: Any ) -> _models.RenewCloudEventLocksResult: - """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - renewed lockTokens, along with other failed lockTokens with their corresponding error - information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param renew_lock_options: RenewLockOptions. Required. - :type renew_lock_options: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with - MutableMapping - :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. - ] - } - """ - + ... @distributed_trace @api_version_validation( method_added_on="2023-10-01-preview", ) - def renew_cloud_event_locks( + def _renew_cloud_event_locks( self, topic_name: str, event_subscription_name: str, - renew_lock_options: Union[_models.RenewLockOptions, JSON, IO[bytes]], + renew_lock_options: Union[_models._models.RenewLockOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.RenewCloudEventLocksResult: """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py index 3b2a6afdde76..cde0db4f1926 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py @@ -5,12 +5,30 @@ """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import base64 import json import sys -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error +from functools import wraps +from typing import ( + Any, + Callable, + Dict, + IO, + List, + Optional, + TypeVar, + Union, + overload, + TYPE_CHECKING, +) + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.messaging import CloudEvent from azure.core.tracing.decorator import distributed_trace from azure.core.pipeline import PipelineResponse @@ -18,222 +36,402 @@ from azure.core.utils import case_insensitive_dict from ._operations import EventGridClientOperationsMixin as OperationsMixin -from .._model_base import _deserialize -from ..models._patch import ReceiveResult, ReceiveDetails +from .._model_base import _deserialize +from ..models._patch import ( + ReceiveResult, + ReceiveDetails, +) from .. import models as _models +from ..models._models import AcknowledgeOptions, ReleaseOptions, RejectOptions, RenewLockOptions +from .._validation import api_version_validation + +from .._legacy import EventGridEvent +from .._legacy._helpers import _from_cncf_events, _is_eventgrid_event from .._serialization import Serializer + if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -T = TypeVar('T') -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +T = TypeVar("T") +ClsType = Optional[ + Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any] +] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False +if TYPE_CHECKING: + from cloudevents.http.event import CloudEvent as CNCFCloudEvent + +EVENT_TYPES_BASIC = Union[ + CloudEvent, + List[CloudEvent], + Dict[str, Any], + List[Dict[str, Any]], + EventGridEvent, + List[EventGridEvent], + "CNCFCloudEvent", + List["CNCFCloudEvent"], +] +EVENT_TYPES_STD = Union[ + CloudEvent, + List[CloudEvent], + Dict[str, Any], + List[Dict[str, Any]], +] + + +def use_standard_only(func): + """Use the standard client only. + + This decorator raises an AttributeError if the client is not a standard client. + + :param func: The function to decorate. + :type func: Callable + :return: The decorated function. + :rtype: Callable + """ + + @wraps(func) + def wrapper(self, *args, **kwargs): + if self._level == "Basic": # pylint: disable=protected-access + raise AttributeError( + "The basic client is not supported for this operation." + ) + return func(self, *args, **kwargs) + + return wrapper + + +def validate_args(**kwargs: Any): + kwargs_mapping = kwargs.pop("kwargs_mapping", None) + + def decorator(func): + @wraps(func) + def wrapper(self, *args: Any, **kwargs: Any) -> T: + selected_client_level = self._level # pylint: disable=protected-access + + if kwargs_mapping: + unsupported_kwargs = { + arg: level + for level, arguments in kwargs_mapping.items() + for arg in arguments + if arg + in kwargs.keys() # pylint: disable=consider-iterating-dictionary + and selected_client_level != level + } + + error_strings = [] + if unsupported_kwargs: + error_strings += [ + f"'{param}' is not available for the {selected_client_level} client. " + f"Use the {level} client.\n" + for param, level in unsupported_kwargs.items() + ] + if len(error_strings) > 0: + raise ValueError("".join(error_strings)) + + return func(self, *args, **kwargs) + + return wrapper + + return decorator + class EventGridClientOperationsMixin(OperationsMixin): + @overload - def publish_cloud_events( + def send( self, - topic_name: str, - body: List[CloudEvent], + events: EVENT_TYPES_BASIC, *, - binary_mode: bool = False, - content_type: str = "application/cloudevents-batch+json; charset=utf-8", - **kwargs: Any + channel_name: Optional[str] = None, + content_type: Optional[str] = None, + **kwargs: Any, ) -> None: - """Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + """Send events to the Event Grid Basic Service. + + :param event: The event to send. + :type event: CloudEvent or List[CloudEvent] or EventGridEvent or List[EventGridEvent] + or Dict[str, Any] or List[Dict[str, Any]] or CNCFCloudEvent or List[CNCFCloudEvent] + :keyword channel_name: The name of the channel to send the event to. + :paramtype channel_name: str or None + :keyword content_type: The content type of the event. If not specified, the default value is + "application/cloudevents+json; charset=utf-8". + :paramtype content_type: str or None - :param topic_name: Topic Name. Required. - :type topic_name: str - :param body: Array of Cloud Events being published. Required. - :type body: list[~azure.core.messaging.CloudEvent] - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. If 'datacontenttype` is not specified, - the default content type is `application/cloudevents-batch+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents-batch+json; - charset=utf-8". - :paramtype content_type: str :return: None :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: """ + ... @overload - def publish_cloud_events( + def send( self, topic_name: str, - body: CloudEvent, + events: EVENT_TYPES_STD, *, binary_mode: bool = False, - content_type: str = "application/cloudevents+json; charset=utf-8", - **kwargs: Any + content_type: Optional[str] = None, + **kwargs: Any, ) -> None: - """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + """Send events to the Event Grid Namespace Service. - :param topic_name: Topic Name. Required. + :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param body: Single Cloud Event being published. Required. - :type body: ~azure.core.messaging.CloudEvent - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If `datacontenttype` is not specified, the default content type is `application/cloudevents+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents+json; - charset=utf-8". - :paramtype content_type: str + :param event: The event to send. + :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default + value is False. + :paramtype binary_mode: bool + :keyword content_type: The content type of the event. If not specified, the default value is + "application/cloudevents+json; charset=utf-8". + :paramtype content_type: str or None + :return: None :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: """ + ... - @overload - def publish_cloud_events( - self, - topic_name: str, - body: Dict[str, Any], - *, - binary_mode: bool = False, - content_type: str = "application/cloudevents+json; charset=utf-8", - **kwargs: Any - ) -> None: - """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + @validate_args( + kwargs_mapping={ + "Basic": ["channel_name"], + "Standard": ["binary_mode"], + } + ) + @distributed_trace + def send(self, *args, **kwargs) -> None: + """Send events to the Event Grid Service. - :param topic_name: Topic Name. Required. + :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param body: Single Cloud Event being published. Required. - :type body: dict[str, Any] - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If `datacontenttype` is not specified, the default content type is `application/cloudevents+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents+json; - charset=utf-8". + :param event: The event to send. + :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + or CNCFCloudEvent or List[CNCFCloudEvent] or EventGridEvent or List[EventGridEvent] + :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default + value is False. + :paramtype binary_mode: bool + :keyword channel_name: The name of the channel to send the event to. + :paramtype channel_name: str or None + :keyword content_type: The content type of the event. If not specified, the default value is + "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def publish_cloud_events( - self, - topic_name: str, - body: List[Dict[str, Any]], - *, - binary_mode: bool = False, - content_type: str = "application/cloudevents-batch+json; charset=utf-8", - **kwargs: Any - ) -> None: - """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. - :param topic_name: Topic Name. Required. - :type topic_name: str - :param body: Batch of Cloud Events being published. Required. - :type body: list[dict[str, Any]] - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If 'datacontenttype` is not specified, the default content type is `application/cloudevents-batch+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents-batch+json; charset=utf-8". - :paramtype content_type: str :return: None :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: + + A single instance or a list of dictionaries, CloudEvents are accepted. In the case of an Azure Event Grid + Basic Resource, EventGridEvent(s) and CNCFCloudEvents are also accepted. + + .. admonition:: Example: + + .. literalinclude:: ../samples/sync_samples/eventgrid_client_samples/sample_publish_operation.py + :start-after: [START publish_cloud_event] + :end-before: [END publish_cloud_event] + :language: python + :dedent: 0 + :caption: Publishing a Cloud Event to a Namespace Topic. + + .. 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: 0 + :caption: Publishing a CloudEvent to a Basic Topic. """ - - @distributed_trace - def publish_cloud_events( + # Check kwargs + channel_name = kwargs.pop("channel_name", None) + binary_mode = kwargs.pop("binary_mode", False) + topic_name = kwargs.pop("topic_name", None) + events = kwargs.pop("events", None) + + # both there + if len(args) > 1: + if events is not None: + raise ValueError("events is already passed as a keyword argument.") + if topic_name is not None: + raise ValueError("topic_name is already passed as a keyword argument.") + events = args[1] + topic_name = args[0] + + elif len(args) == 1: + if events is not None: + if topic_name is not None: + raise ValueError( + "topic_name is already passed as a keyword argument." + ) + topic_name = args[0] + else: + events = args[0] + + if self._level == "Standard" and topic_name is None: + raise ValueError("Topic name is required for standard level client.") + + # check binary mode + if binary_mode: + self._send_binary(topic_name, events, **kwargs) + else: + # If not binary_mode send whatever event is passed + + # If a cloud event dict, convert to CloudEvent for serializing + try: + if isinstance(events, dict): + events = CloudEvent.from_dict(events) + if isinstance(events, list) and isinstance(events[0], dict): + events = [CloudEvent.from_dict(e) for e in events] + except Exception: # pylint: disable=broad-except + pass + + if self._level == "Standard": + kwargs["content_type"] = kwargs.get( + "content_type", "application/cloudevents-batch+json; charset=utf-8" + ) + if not isinstance(events, list): + events = [events] + + if isinstance(events[0], EventGridEvent) or _is_eventgrid_event(events[0]): + raise TypeError("EventGridEvent is not supported for standard level client.") + try: + # Try to send via namespace + self._send(topic_name, _serialize_events(events), **kwargs) + except Exception as exception: # pylint: disable=broad-except + self._http_response_error_handler(exception, "Standard") + raise exception + else: + try: + self._send(events, channel_name=channel_name, **kwargs) + except Exception as exception: + self._http_response_error_handler(exception, "Basic") + raise exception + + def _send_binary(self, topic_name, events, **kwargs): + # If data is passed as a dictionary, make sure it is a CloudEvent + try: + if isinstance(events, dict): + events = CloudEvent.from_dict(events) + except AttributeError: + raise TypeError( # pylint: disable=raise-missing-from + "Binary mode is only supported for type CloudEvent." + ) + + # If data is a cloud event, convert to an HTTP Request in binary mode + # Content type becomes the data content type + if isinstance(events, CloudEvent): + self._publish(topic_name, events, self._config.api_version, **kwargs) + else: + raise TypeError("Binary mode is only supported for type CloudEvent.") + + def _http_response_error_handler(self, exception, level): + if isinstance(exception, HttpResponseError): + if exception.status_code == 400: + raise HttpResponseError( + "Invalid event data. Please check the data and try again." + ) from exception + if exception.status_code == 404: + raise ResourceNotFoundError( + "Resource not found. " + f"Please check that the level set on the client, {level}, corresponds to the correct " + "endpoint and/or topic name." + ) from exception + raise exception + + def _publish( self, topic_name: str, - body: Union[List[CloudEvent], CloudEvent, List[Dict[str, Any]], Dict[str, Any]], - *, - binary_mode: bool = False, - **kwargs + event: Any, + api_version: str, + **kwargs: Any, ) -> None: - """Publish Batch Cloud Event or Events to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. - :param topic_name: Topic Name. Required. - :type topic_name: str - :param body: Cloud Event or array of Cloud Events being published. Required. - :type body: ~azure.core.messaging.CloudEvent or list[~azure.core.messaging.CloudEvent] or dict[str, any] or list[dict[str, any]] - :keyword bool binary_mode: Whether to publish the events in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If not specified, the default content type is "application/cloudevents+json; charset=utf-8". - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents+json; - charset=utf-8". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - # Check that the body is a CloudEvent or list of CloudEvents even if dict - if isinstance(body, dict) or (isinstance(body, list) and isinstance(body[0], dict)): - try: - if isinstance(body, list): - body = [CloudEvent.from_dict(event) for event in body] - else: - body = CloudEvent.from_dict(body) - except AttributeError: - raise TypeError("Incorrect type for body. Expected CloudEvent," - " list of CloudEvents, dict, or list of dicts." - " If dict passed, must follow the CloudEvent format.") - - - if isinstance(body, CloudEvent): - kwargs["content_type"] = "application/cloudevents+json; charset=utf-8" - self._publish(topic_name, body, self._config.api_version, binary_mode, **kwargs) - elif isinstance(body, list): - kwargs["content_type"] = "application/cloudevents-batch+json; charset=utf-8" - self._publish(topic_name, body, self._config.api_version, binary_mode, **kwargs) + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models._models.PublishResult] = kwargs.pop( + "cls", None + ) # pylint: disable=protected-access + + content_type = kwargs.pop( # pylint: disable=unused-variable + "content_type", None + ) + # Given that we know the cloud event is binary mode, we can convert it to a HTTP request + http_request = _to_http_request( + topic_name=topic_name, + api_version=api_version, + headers=_headers, + params=_params, + event=event, + **kwargs, + ) + + _stream = kwargs.pop("stream", False) + + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + http_request.url = self._client.format_url( + http_request.url, **path_format_arguments + ) + + # pipeline_response: PipelineResponse = self.send_request(http_request, **kwargs) + pipeline_response: PipelineResponse = ( + self._client._pipeline.run( # pylint: disable=protected-access + http_request, stream=_stream, **kwargs + ) + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error( + status_code=response.status_code, response=response, error_map=error_map + ) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() else: - raise TypeError("Incorrect type for body. Expected CloudEvent," - " list of CloudEvents, dict, or list of dicts." - " If dict passed, must follow the CloudEvent format.") + deserialized = _deserialize( + _models._models.PublishResult, # pylint: disable=protected-access + response.json(), + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + @use_standard_only @distributed_trace - def receive_cloud_events( + def receive( self, topic_name: str, - event_subscription_name: str, + subscription_name: str, *, max_events: Optional[int] = None, max_wait_time: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> ReceiveResult: """Receive Batch of Cloud Events from the Event Subscription. :param topic_name: Topic Name. Required. :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str :keyword max_events: Max Events count to be received. Minimum value is 1, while maximum value is 100 events. If not specified, the default value is 1. Default value is None. :paramtype max_events: int @@ -243,8 +441,6 @@ def receive_cloud_events( value is 10 seconds, while maximum value is 120 seconds. If not specified, the default value is 60 seconds. Default value is None. :paramtype max_wait_time: int - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: ReceiveResult. The ReceiveResult is compatible with MutableMapping :rtype: ~azure.eventgrid.models.ReceiveResult :raises ~azure.core.exceptions.HttpResponseError: @@ -253,10 +449,10 @@ def receive_cloud_events( detail_items = [] received_result = self._receive_cloud_events( topic_name, - event_subscription_name, + subscription_name, max_events=max_events, max_wait_time=max_wait_time, - **kwargs + **kwargs, ) for detail_item in received_result.value: deserialized_cloud_event = CloudEvent.from_dict(detail_item.event) @@ -270,159 +466,262 @@ def receive_cloud_events( receive_result_deserialized = ReceiveResult(value=detail_items) return receive_result_deserialized - def _publish(self, topic_name: str, event: Any, api_version: str, binary_mode: Optional[bool] = False, **kwargs: Any) -> None: - - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError - } - error_map.update(kwargs.pop('error_map', {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} + @use_standard_only + @distributed_trace + def acknowledge( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + **kwargs: Any, + ) -> _models.AcknowledgeResult: + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + acknowledged lockTokens, along with other failed lockTokens with their corresponding error + information. Successfully acknowledged events will no longer be available to any consumer. - cls: ClsType[_models._models.PublishResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping + :rtype: ~azure.eventgrid.models.AcknowledgeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = AcknowledgeOptions(lock_tokens=lock_tokens) + return super()._acknowledge_cloud_events( + topic_name=topic_name, + event_subscription_name=subscription_name, + acknowledge_options=options, + **kwargs, ) - content_type: str = kwargs.pop('content_type', _headers.pop('content-type', "application/cloudevents+json; charset=utf-8")) + @use_standard_only + @distributed_trace + @api_version_validation( + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, + ) + def release( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + **kwargs: Any, + ) -> _models.ReleaseResult: + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released + lockTokens, along with other failed lockTokens with their corresponding error information. - # Given that we know the cloud event is binary mode, we can convert it to a HTTP request - http_request = _to_http_request( + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay + :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping + :rtype: ~azure.eventgrid.models.ReleaseResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = ReleaseOptions(lock_tokens=lock_tokens) + return super()._release_cloud_events( topic_name=topic_name, - api_version=api_version, - headers=_headers, - params=_params, - content_type=content_type, - event=event, - binary_mode=binary_mode, - **kwargs + event_subscription_name=subscription_name, + release_options=options, + release_delay_in_seconds=release_delay_in_seconds, + **kwargs, ) - _stream = kwargs.pop("stream", False) - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + @use_standard_only + @distributed_trace + def reject( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + **kwargs: Any, + ) -> _models.RejectResult: + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. - # pipeline_response: PipelineResponse = self.send_request(http_request, **kwargs) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - http_request, - stream=_stream, - **kwargs + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :return: RejectResult. The RejectResult is compatible with MutableMapping + :rtype: ~azure.eventgrid.models.RejectResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = RejectOptions(lock_tokens=lock_tokens) + return super()._reject_cloud_events( + topic_name=topic_name, + event_subscription_name=subscription_name, + reject_options=options, + **kwargs, ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize( - _models._models.PublishResult, # pylint: disable=protected-access - response.json() - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + @use_standard_only + @distributed_trace + @api_version_validation( + method_added_on="2023-10-01-preview", + ) + def renew_locks( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + **kwargs: Any, + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. - return deserialized # type: ignore + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = RenewLockOptions(lock_tokens=lock_tokens) + return super()._renew_cloud_event_locks( + topic_name=topic_name, + event_subscription_name=subscription_name, + renew_lock_options=options, + **kwargs, + ) -def _to_http_request(topic_name: str, **kwargs: Any) -> HttpRequest: +def _to_http_request(topic_name: str, **kwargs: Any) -> HttpRequest: # Create a HTTP request for a binary mode CloudEvent _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) event = kwargs.pop("event") - binary_mode = kwargs.pop("binary_mode", False) - - if binary_mode: - # Content of the request is the data, if already in binary - no work needed - try: - if isinstance(event.data, bytes): - _content = event.data - else: - raise TypeError("CloudEvent data must be bytes when in binary mode." - "Did you forget to call `json.dumps()` and/or `encode()` on CloudEvent data?") - except AttributeError: - raise TypeError("Binary mode is not supported for batch CloudEvents. Set `binary_mode` to False when passing in a batch of CloudEvents.") - else: - # Content of the request is the serialized CloudEvent or serialized List[CloudEvent] - _content = _serialize_cloud_events(event) - + # Content of the request is the data, if already in binary - no work needed + try: + if isinstance(event.data, bytes): + _content = event.data + else: + raise TypeError( + "CloudEvent data must be bytes when in binary mode." + "Did you forget to call `json.dumps()` and/or `encode()` on CloudEvent data?" + ) + except AttributeError as exc: + raise TypeError( + "Binary mode is not supported for batch CloudEvents." + " Set `binary_mode` to False when passing in a batch of CloudEvents." + ) from exc + # content_type must be CloudEvent DataContentType when in binary mode - default_content_type = kwargs.pop('content_type', _headers.pop('content-type', "application/cloudevents+json; charset=utf-8")) - content_type: str = event.datacontenttype if (binary_mode and event.datacontenttype) else default_content_type + if not event.datacontenttype: + raise TypeError("CloudEvent datacontenttype must be set when in binary mode.") + content_type: str = event.datacontenttype - api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) - accept = _headers.pop('Accept', "application/json") + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", "2023-10-01-preview") + ) + accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/topics/{topicName}:publish" path_format_arguments = { - "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), + "topicName": _SERIALIZER.url("topic_name", topic_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['content-type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - if binary_mode: - # Cloud Headers - _headers['ce-source'] = _SERIALIZER.header('ce-source', event.source, 'str') - _headers['ce-type'] = _SERIALIZER.header('ce-type', event.type, 'str') - if event.specversion: - _headers['ce-specversion'] = _SERIALIZER.header('ce-specversion', event.specversion, 'str') - if event.id: - _headers['ce-id'] = _SERIALIZER.header('ce-id', event.id, 'str') - if event.time: - _headers['ce-time'] = _SERIALIZER.header('ce-time', event.time, 'str') - if event.dataschema: - _headers['ce-dataschema'] = _SERIALIZER.header('ce-dataschema', event.dataschema, 'str') - if event.subject: - _headers['ce-subject'] = _SERIALIZER.header('ce-subject', event.subject, 'str') - if event.extensions: - for extension, value in event.extensions.items(): - _headers[f'ce-{extension}'] = _SERIALIZER.header('ce-extensions', value, 'str') + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + # Cloud Headers + _headers["ce-source"] = _SERIALIZER.header("ce-source", event.source, "str") + _headers["ce-type"] = _SERIALIZER.header("ce-type", event.type, "str") + if event.specversion: + _headers["ce-specversion"] = _SERIALIZER.header( + "ce-specversion", event.specversion, "str" + ) + if event.id: + _headers["ce-id"] = _SERIALIZER.header("ce-id", event.id, "str") + if event.time: + _headers["ce-time"] = _SERIALIZER.header("ce-time", event.time, "str") + if event.dataschema: + _headers["ce-dataschema"] = _SERIALIZER.header( + "ce-dataschema", event.dataschema, "str" + ) + if event.subject: + _headers["ce-subject"] = _SERIALIZER.header("ce-subject", event.subject, "str") + if event.extensions: + for extension, value in event.extensions.items(): + _headers[f"ce-{extension}"] = _SERIALIZER.header( + "ce-extensions", value, "str" + ) return HttpRequest( method="POST", url=_url, params=_params, headers=_headers, - content=_content, # pass through content - **kwargs + content=_content, # pass through content + **kwargs, ) -def _serialize_cloud_events(events: Union[CloudEvent, List[CloudEvent]]) -> None: - # Serialize CloudEvent or List[CloudEvent] into a JSON string - is_list = isinstance(events, list) - data = {} - list_data = [] - for event in events if isinstance(events, list) else [events]: + +def _serialize_events(events): + if isinstance(events[0], CloudEvent): + internal_body_list = [] + for item in events: + internal_body_list.append(_serialize_cloud_event(item)) + return json.dumps(internal_body_list) + try: + serialize = Serializer() + body = serialize.body(events, "[object]") + if body is None: + data = None + else: + data = json.dumps(body) + + return data + except AttributeError: + return events + + +def _serialize_cloud_event(event): + try: + data = {} # CloudEvent required fields but validate they are not set to None if event.type: - data["type"] = _SERIALIZER.body(event.type, "str") + data["type"] = _SERIALIZER.body(event.type, "str") if event.specversion: data["specversion"] = _SERIALIZER.body(event.specversion, "str") if event.source: data["source"] = _SERIALIZER.body(event.source, "str") if event.id: data["id"] = _SERIALIZER.body(event.id, "str") - + # Check if data is bytes and serialize to base64 if isinstance(event.data, bytes): data["data_base64"] = _SERIALIZER.serialize_bytearray(event.data) @@ -439,13 +738,9 @@ def _serialize_cloud_events(events: Union[CloudEvent, List[CloudEvent]]) -> None for extension, value in event.extensions.items(): data[extension] = _SERIALIZER.body(value, "str") - # If single cloud event return the data - if not is_list: - return json.dumps(data) - else: - list_data.append(data) - # If list of cloud events return the list - return json.dumps(list_data) + return data + except AttributeError: + return [_from_cncf_events(e) for e in event] __all__: List[str] = [ diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py index 9ac00715fa22..bc579af964bc 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_patch.py @@ -6,13 +6,94 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import List, Union, Optional, Any +from enum import Enum + +from azure.core import CaseInsensitiveEnumMeta +from azure.core.credentials import ( + AzureKeyCredential, + TokenCredential, + AzureSasCredential, +) + from ._legacy import ( EventGridPublisherClient, SystemEventNames, EventGridEvent, generate_sas, ) +from ._client import ( + EventGridClient as InternalEventGridClient, +) +from ._serialization import Serializer, Deserializer + + +class ClientLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + STANDARD = ("Standard",) + BASIC = "Basic" + + +DEFAULT_STANDARD_API_VERSION = "2023-10-01-preview" +DEFAULT_BASIC_API_VERSION = "2018-01-01" + + +class EventGridClient(InternalEventGridClient): + """ + Azure Messaging EventGrid Client. + + :param endpoint: The endpoint to the Event Grid resource. + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value for namespaces is + "2023-10-01-preview". Default value for basic is "2018-01-01". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str or None + :keyword level: The level of client to use. Known values are + `Standard` and `Basic`. Default value is `Standard`. + `Standard` is used for working with a namespace topic. + `Basic` is used for working with a basic topic. + :paramtype level: str + """ + + def __init__( + self, + endpoint: str, + credential: Union[AzureKeyCredential, AzureSasCredential, "TokenCredential"], + *, + api_version: Optional[str] = None, + level: Union[str, ClientLevel] = "Standard", + **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._level = level + + if level == ClientLevel.BASIC: + self._client = EventGridPublisherClient( + endpoint, + credential, + api_version=api_version or DEFAULT_BASIC_API_VERSION, + ) # type:ignore[assignment] + self._send = self._client.send # type:ignore[attr-defined] + elif level == ClientLevel.STANDARD: + if isinstance(credential, AzureSasCredential): + raise TypeError( + "SAS token authentication is not supported for the standard client." + ) + super().__init__( + endpoint=endpoint, + credential=credential, + api_version=api_version or DEFAULT_STANDARD_API_VERSION, + **kwargs + ) + + self._send = self._publish_cloud_events + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + def patch_sdk(): """Do not remove from this file. @@ -27,4 +108,6 @@ def patch_sdk(): "SystemEventNames", "EventGridEvent", "generate_sas", + "EventGridClient", + "ClientLevel", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py index 6c53eb888303..149d797cbe4e 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._client import EventGridClient +from ._patch import EventGridClient try: from ._patch import __all__ as _patch_all diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py index c166e5de9c64..5d63b0e4eaa0 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._operations import EventGridClientOperationsMixin +from ._patch import EventGridClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py index 5583df5b4b9e..8640bcff8730 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py @@ -378,75 +378,18 @@ async def _receive_cloud_events( # pylint: disable=protected-access @overload - async def acknowledge_cloud_events( + async def _acknowledge_cloud_events( # pylint: disable=protected-access self, topic_name: str, event_subscription_name: str, - acknowledge_options: _models.AcknowledgeOptions, + acknowledge_options: _models._models.AcknowledgeOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - acknowledged lockTokens, along with other failed lockTokens with their corresponding error - information. Successfully acknowledged events will no longer be available to any consumer. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param acknowledge_options: AcknowledgeOptions. Required. - :type acknowledge_options: ~azure.eventgrid.models.AcknowledgeOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.AcknowledgeResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - acknowledge_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. - ] - } - """ - + ... @overload - async def acknowledge_cloud_events( + async def _acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -455,59 +398,9 @@ async def acknowledge_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - acknowledged lockTokens, along with other failed lockTokens with their corresponding error - information. Successfully acknowledged events will no longer be available to any consumer. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param acknowledge_options: AcknowledgeOptions. Required. - :type acknowledge_options: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.AcknowledgeResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. - ] - } - """ - + ... @overload - async def acknowledge_cloud_events( + async def _acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -516,64 +409,14 @@ async def acknowledge_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - acknowledged lockTokens, along with other failed lockTokens with their corresponding error - information. Successfully acknowledged events will no longer be available to any consumer. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param acknowledge_options: AcknowledgeOptions. Required. - :type acknowledge_options: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.AcknowledgeResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully acknowledged cloud - events. Required. - ] - } - """ - + ... @distributed_trace_async - async def acknowledge_cloud_events( + async def _acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - acknowledge_options: Union[_models.AcknowledgeOptions, JSON, IO[bytes]], + acknowledge_options: Union[_models._models.AcknowledgeOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.AcknowledgeResult: """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the @@ -695,19 +538,64 @@ async def acknowledge_cloud_events( + @overload + @api_version_validation( + params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + ) # pylint: disable=protected-access + async def _release_cloud_events( # pylint: disable=protected-access + self, + topic_name: str, + event_subscription_name: str, + release_options: _models._models.ReleaseOptions, + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ReleaseResult: + ... + @overload + @api_version_validation( + params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + ) + async def _release_cloud_events( + self, + topic_name: str, + event_subscription_name: str, + release_options: JSON, + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ReleaseResult: + ... @overload @api_version_validation( params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, ) - async def release_cloud_events( + async def _release_cloud_events( self, topic_name: str, event_subscription_name: str, - release_options: _models.ReleaseOptions, + release_options: IO[bytes], *, release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any + ) -> _models.ReleaseResult: + ... + + @distributed_trace_async + @api_version_validation( + params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, + ) + async def _release_cloud_events( + self, + topic_name: str, + event_subscription_name: str, + release_options: Union[_models._models.ReleaseOptions, JSON, IO[bytes]], + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + **kwargs: Any ) -> _models.ReleaseResult: """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request is successfully accepted. The response body will include the set of successfully released @@ -717,14 +605,12 @@ async def release_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param release_options: ReleaseOptions. Required. - :type release_options: ~azure.eventgrid.models.ReleaseOptions + :param release_options: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, + IO[bytes] Required. + :type release_options: ~azure.eventgrid.models.ReleaseOptions or JSON or IO[bytes] :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. Known values are: 0, 10, 60, 600, and 3600. Default value is None. :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping :rtype: ~azure.eventgrid.models.ReleaseResult :raises ~azure.core.exceptions.HttpResponseError: @@ -768,346 +654,84 @@ async def release_cloud_events( ] } """ + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + } + error_map.update(kwargs.pop('error_map', {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + cls: ClsType[_models.ReleaseResult] = kwargs.pop( + 'cls', None + ) + + content_type = content_type or "application/json" + _content = None + if isinstance(release_options, (IOBase, bytes)): + _content = release_options + else: + _content = json.dumps(release_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_event_grid_release_cloud_events_request( + topic_name=topic_name, + event_subscription_name=event_subscription_name, + release_delay_in_seconds=release_delay_in_seconds, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, + stream=_stream, + **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models.ReleaseResult, + response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload - @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, - ) - async def release_cloud_events( + async def _reject_cloud_events( # pylint: disable=protected-access self, topic_name: str, event_subscription_name: str, - release_options: JSON, + reject_options: _models._models.RejectOptions, *, - release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully released - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param release_options: ReleaseOptions. Required. - :type release_options: JSON - :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. - Known values are: 0, 10, 60, 600, and 3600. Default value is None. - :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.ReleaseResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. - ] - } - """ - - @overload - @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, - ) - async def release_cloud_events( - self, - topic_name: str, - event_subscription_name: str, - release_options: IO[bytes], - *, - release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully released - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param release_options: ReleaseOptions. Required. - :type release_options: IO[bytes] - :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. - Known values are: 0, 10, 60, 600, and 3600. Default value is None. - :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.ReleaseResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. - ] - } - """ - - - @distributed_trace_async - @api_version_validation( - params_added_on={'2023-10-01-preview': ['release_delay_in_seconds']}, - ) - async def release_cloud_events( - self, - topic_name: str, - event_subscription_name: str, - release_options: Union[_models.ReleaseOptions, JSON, IO[bytes]], - *, - release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, - **kwargs: Any - ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully released - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param release_options: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, - IO[bytes] Required. - :type release_options: ~azure.eventgrid.models.ReleaseOptions or JSON or IO[bytes] - :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. - Known values are: 0, 10, 60, 600, and 3600. Default value is None. - :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay - :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.ReleaseResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - release_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully released cloud - events. Required. - ] - } - """ - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError - } - error_map.update(kwargs.pop('error_map', {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) - cls: ClsType[_models.ReleaseResult] = kwargs.pop( - 'cls', None - ) - - content_type = content_type or "application/json" - _content = None - if isinstance(release_options, (IOBase, bytes)): - _content = release_options - else: - _content = json.dumps(release_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_event_grid_release_cloud_events_request( - topic_name=topic_name, - event_subscription_name=event_subscription_name, - release_delay_in_seconds=release_delay_in_seconds, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, - stream=_stream, - **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize( - _models.ReleaseResult, - response.json() - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - - - @overload - async def reject_cloud_events( - self, - topic_name: str, - event_subscription_name: str, - reject_options: _models.RejectOptions, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RejectResult: - """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully rejected - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param reject_options: RejectOptions. Required. - :type reject_options: ~azure.eventgrid.models.RejectOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RejectResult. The RejectResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.RejectResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - reject_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. - ] - } - """ - + ) -> _models.RejectResult: + ... @overload - async def reject_cloud_events( + async def _reject_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -1116,58 +740,9 @@ async def reject_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully rejected - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param reject_options: RejectOptions. Required. - :type reject_options: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RejectResult. The RejectResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.RejectResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. - ] - } - """ - + ... @overload - async def reject_cloud_events( + async def _reject_cloud_events( self, topic_name: str, event_subscription_name: str, @@ -1176,63 +751,14 @@ async def reject_cloud_events( content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request - is successfully accepted. The response body will include the set of successfully rejected - lockTokens, along with other failed lockTokens with their corresponding error information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param reject_options: RejectOptions. Required. - :type reject_options: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: RejectResult. The RejectResult is compatible with MutableMapping - :rtype: ~azure.eventgrid.models.RejectResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully rejected cloud - events. Required. - ] - } - """ - + ... @distributed_trace_async - async def reject_cloud_events( + async def _reject_cloud_events( self, topic_name: str, event_subscription_name: str, - reject_options: Union[_models.RejectOptions, JSON, IO[bytes]], + reject_options: Union[_models._models.RejectOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.RejectResult: """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request @@ -1356,80 +882,22 @@ async def reject_cloud_events( @overload @api_version_validation( method_added_on="2023-10-01-preview", - ) - async def renew_cloud_event_locks( + ) # pylint: disable=protected-access + async def _renew_cloud_event_locks( # pylint: disable=protected-access self, topic_name: str, event_subscription_name: str, - renew_lock_options: _models.RenewLockOptions, + renew_lock_options: _models._models.RenewLockOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RenewCloudEventLocksResult: - """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - renewed lockTokens, along with other failed lockTokens with their corresponding error - information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param renew_lock_options: RenewLockOptions. Required. - :type renew_lock_options: ~azure.eventgrid.models.RenewLockOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with - MutableMapping - :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - renew_lock_options = { - "lockTokens": [ - "str" # Array of lock tokens. Required. - ] - } - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. - ] - } - """ - + ... @overload @api_version_validation( method_added_on="2023-10-01-preview", ) - async def renew_cloud_event_locks( + async def _renew_cloud_event_locks( self, topic_name: str, event_subscription_name: str, @@ -1438,63 +906,12 @@ async def renew_cloud_event_locks( content_type: str = "application/json", **kwargs: Any ) -> _models.RenewCloudEventLocksResult: - """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - renewed lockTokens, along with other failed lockTokens with their corresponding error - information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param renew_lock_options: RenewLockOptions. Required. - :type renew_lock_options: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with - MutableMapping - :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. - ] - } - """ - + ... @overload @api_version_validation( method_added_on="2023-10-01-preview", ) - async def renew_cloud_event_locks( + async def _renew_cloud_event_locks( self, topic_name: str, event_subscription_name: str, @@ -1503,68 +920,17 @@ async def renew_cloud_event_locks( content_type: str = "application/json", **kwargs: Any ) -> _models.RenewCloudEventLocksResult: - """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the - request is successfully accepted. The response body will include the set of successfully - renewed lockTokens, along with other failed lockTokens with their corresponding error - information. - - :param topic_name: Topic Name. Required. - :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str - :param renew_lock_options: RenewLockOptions. Required. - :type renew_lock_options: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with - MutableMapping - :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "failedLockTokens": [ - { - "error": { - "code": "str", # One of a server-defined set of - error codes. Required. - "message": "str", # A human-readable representation - of the error. Required. - "details": [ - ... - ], - "innererror": { - "code": "str", # Optional. One of a - server-defined set of error codes. - "innererror": ... - }, - "target": "str" # Optional. The target of the error. - }, - "lockToken": "str" # The lock token of an entry in the - request. Required. - } - ], - "succeededLockTokens": [ - "str" # Array of lock tokens for the successfully renewed locks. - Required. - ] - } - """ - + ... @distributed_trace_async @api_version_validation( method_added_on="2023-10-01-preview", ) - async def renew_cloud_event_locks( + async def _renew_cloud_event_locks( self, topic_name: str, event_subscription_name: str, - renew_lock_options: Union[_models.RenewLockOptions, JSON, IO[bytes]], + renew_lock_options: Union[_models._models.RenewLockOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.RenewCloudEventLocksResult: """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py index 6b20e911093d..70d55e829fb9 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py @@ -5,228 +5,264 @@ """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List, overload, Union, Any, Optional, Callable, Dict, TypeVar +from typing import List, overload, Union, Any, Optional, Callable, Dict, TypeVar, IO import sys from azure.core.messaging import CloudEvent -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.pipeline import PipelineResponse from azure.core.rest import HttpRequest, AsyncHttpResponse from azure.core.utils import case_insensitive_dict from ...models._patch import ReceiveResult, ReceiveDetails -from ..._operations._patch import _to_http_request +from ..._operations._patch import _to_http_request, use_standard_only from ._operations import EventGridClientOperationsMixin as OperationsMixin from ... import models as _models +from ...models._models import AcknowledgeOptions, ReleaseOptions, RejectOptions, RenewLockOptions from ..._model_base import _deserialize +from ..._validation import api_version_validation + +from ..._operations._patch import ( + _serialize_events, + EVENT_TYPES_BASIC, + EVENT_TYPES_STD, + validate_args, +) + +from ..._legacy import EventGridEvent +from ..._legacy._helpers import _is_eventgrid_event + if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -T = TypeVar('T') -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +T = TypeVar("T") +ClsType = Optional[ + Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any] +] + class EventGridClientOperationsMixin(OperationsMixin): @overload - async def publish_cloud_events( + async def send( self, - topic_name: str, - body: List[CloudEvent], + events: EVENT_TYPES_BASIC, *, - binary_mode: bool = False, - content_type: str = "application/cloudevents-batch+json; charset=utf-8", - **kwargs: Any + channel_name: Optional[str] = None, + content_type: Optional[str] = None, + **kwargs: Any, ) -> None: - """Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + """Send events to the Event Grid Basic Service. + + :param event: The event to send. + :type event: CloudEvent or List[CloudEvent] or EventGridEvent or List[EventGridEvent] + or Dict[str, Any] or List[Dict[str, Any]] or CNCFCloudEvent or List[CNCFCloudEvent] + :keyword channel_name: The name of the channel to send the event to. + :paramtype channel_name: str or None + :keyword content_type: The content type of the event. If not specified, the default value is + "application/cloudevents+json; charset=utf-8". + :paramtype content_type: str or None - :param topic_name: Topic Name. Required. - :type topic_name: str - :param body: Array of Cloud Events being published. Required. - :type body: list[~azure.core.messaging.CloudEvent] - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If 'datacontenttype` is not specified the default content type is `application/cloudevents-batch+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents-batch+json; - charset=utf-8". - :paramtype content_type: str :return: None :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: """ + ... @overload - async def publish_cloud_events( + async def send( self, topic_name: str, - body: CloudEvent, + events: EVENT_TYPES_STD, *, binary_mode: bool = False, - content_type: str = "application/cloudevents+json; charset=utf-8", - **kwargs: Any + content_type: Optional[str] = None, + **kwargs: Any, ) -> None: - """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + """Send events to the Event Grid Namespace Service. - :param topic_name: Topic Name. Required. + :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param body: Single Cloud Event being published. Required. - :type body: ~azure.core.messaging.CloudEvent - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If `datacontenttype` is not specified, the default content type is `application/cloudevents+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents+json; - charset=utf-8". - :paramtype content_type: str + :param event: The event to send. + :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default + value is False. + :paramtype binary_mode: bool + :keyword content_type: The content type of the event. If not specified, the default value is + "application/cloudevents+json; charset=utf-8". + :paramtype content_type: str or None + :return: None :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: """ + ... - @overload - async def publish_cloud_events( - self, - topic_name: str, - body: Dict[str, Any], - *, - binary_mode: bool = False, - content_type: str = "application/cloudevents+json; charset=utf-8", - **kwargs: Any - ) -> None: - """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + @validate_args( + kwargs_mapping={ + "Basic": ["channel_name"], + "Standard": ["binary_mode"], + } + ) + @distributed_trace_async + async def send(self, *args, **kwargs) -> None: + """Send events to the Event Grid Namespace Service. - :param topic_name: Topic Name. Required. + :param topic_name: The name of the topic to send the event to. :type topic_name: str - :param body: Single Cloud Event being published. Required. - :type body: dict[str, Any] - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If `datacontenttype` is not specified, the default content type is `application/cloudevents+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents+json; - charset=utf-8". + :param event: The event to send. + :type event: CloudEvent or List[CloudEvent] or Dict[str, Any] or List[Dict[str, Any]] + :keyword binary_mode: Whether to send the event in binary mode. If not specified, the default + value is False. + :paramtype binary_mode: bool + :keyword channel_name: The name of the channel to send the event to. + :paramtype channel_name: str or None + :keyword content_type: The content type of the event. If not specified, the default value is + "application/cloudevents+json; charset=utf-8". :paramtype content_type: str + :return: None :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - @overload - async def publish_cloud_events( - self, - topic_name: str, - body: List[Dict[str, Any]], - *, - binary_mode: bool = False, - content_type: str = "application/cloudevents-batch+json; charset=utf-8", - **kwargs: Any - ) -> None: - """Publish Single Cloud Event to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + A single instance or a list of dictionaries, CloudEvents are accepted. In the case of an Azure Event Grid + Basic Resource, EventGridEvent(s) and CNCFCloudEvents are also accepted. - :param topic_name: Topic Name. Required. - :type topic_name: str - :param body: Batch of Cloud Events being published. Required. - :type body: list[dict[str, Any]] - :keyword bool binary_mode: Whether to publish a CloudEvent in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If 'datacontenttype` is not specified, the default content type is `application/cloudevents-batch+json; charset=utf-8`. - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents+json; - charset=utf-8". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ + .. admonition:: Example: - @distributed_trace_async - async def publish_cloud_events( - self, - topic_name: str, - body: Union[List[CloudEvent], CloudEvent, List[Dict[str, Any]], Dict[str, Any]], - *, - binary_mode: bool = False, - **kwargs - ) -> None: - """Publish Batch Cloud Event or Events to namespace topic. In case of success, the server responds with an - HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return - various error codes. For example, 401: which indicates authorization failure, 403: which - indicates quota exceeded or message is too large, 410: which indicates that specific topic is - not found, 400: for bad request, and 500: for internal server error. + .. literalinclude:: ../samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py + :start-after: [START publish_cloud_event_async] + :end-before: [END publish_cloud_event_async] + :language: python + :dedent: 0 + :caption: Publishing a Cloud Event to a Namespace Topic. - :param topic_name: Topic Name. Required. - :type topic_name: str - :param body: Cloud Event or Array of Cloud Events being published. Required. - :type body: ~azure.core.messaging.CloudEvent or list[~azure.core.messaging.CloudEvent] or dict[str, any] or list[dict[str, any]] - :keyword bool binary_mode: Whether to publish the events in binary mode. Defaults to False. - When True and `datacontenttype` is specified in CloudEvent, content type is set to `datacontenttype`. - If not specified, the default content type is "application/cloudevents+json; charset=utf-8". - Requires CloudEvent data to be passed in as bytes. - :keyword content_type: content type. Default value is "application/cloudevents+json; - charset=utf-8". - :paramtype content_type: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: + .. 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: 0 + :caption: Publishing a CloudEvent to a Basic Topic. """ - - # Check that the body is a CloudEvent or list of CloudEvents even if dict - if isinstance(body, dict) or (isinstance(body, list) and isinstance(body[0], dict)): - try: - if isinstance(body, list): - body = [CloudEvent.from_dict(event) for event in body] - else: - body = CloudEvent.from_dict(body) - except AttributeError: - raise TypeError("Incorrect type for body. Expected CloudEvent," - " list of CloudEvents, dict, or list of dicts." - " If dict passed, must follow the CloudEvent format.") - - - if isinstance(body, CloudEvent): - kwargs["content_type"] = "application/cloudevents+json; charset=utf-8" - await self._publish(topic_name, body, self._config.api_version, binary_mode, **kwargs) - elif isinstance(body, list): - kwargs["content_type"] = "application/cloudevents-batch+json; charset=utf-8" - await self._publish(topic_name, body, self._config.api_version, binary_mode, **kwargs) + # Check kwargs + channel_name = kwargs.pop("channel_name", None) + binary_mode = kwargs.pop("binary_mode", False) + topic_name = kwargs.pop("topic_name", None) + events = kwargs.pop("events", None) + + # both there + if len(args) > 1: + if events is not None: + raise ValueError("events is already passed as a keyword argument.") + if topic_name is not None: + raise ValueError("topic_name is already passed as a keyword argument.") + events = args[1] + topic_name = args[0] + + elif len(args) == 1: + if events is not None: + if topic_name is not None: + raise ValueError( + "topic_name is already passed as a keyword argument." + ) + topic_name = args[0] + else: + events = args[0] + + if self._level == "Standard" and topic_name is None: + raise ValueError("Topic name is required for standard level client.") + + # check binary mode + if binary_mode: + await self._send_binary(topic_name, events, **kwargs) else: - raise TypeError("Incorrect type for body. Expected CloudEvent," - " list of CloudEvents, dict, or list of dicts." - " If dict passed, must follow the CloudEvent format.") + # If no binary_mode is set, send whatever event is passed + # If a cloud event dict, convert to CloudEvent for serializing + try: + if isinstance(events, dict): + events = CloudEvent.from_dict(events) + if isinstance(events, list) and isinstance(events[0], dict): + events = [CloudEvent.from_dict(e) for e in events] + except Exception: # pylint: disable=broad-except + pass + + if self._level == "Standard": + kwargs["content_type"] = kwargs.get( + "content_type", "application/cloudevents-batch+json; charset=utf-8" + ) + if not isinstance(events, list): + events = [events] + + if isinstance(events[0], EventGridEvent) or _is_eventgrid_event(events[0]): + raise TypeError("EventGridEvent is not supported for standard level client.") + try: + # Try to send via namespace + await self._send(topic_name, _serialize_events(events), **kwargs) + except Exception as exception: # pylint: disable=broad-except + self._http_response_error_handler(exception, "Standard") + raise exception + # # If that fails, try to send via basic + # self._last_exception = exception + else: + try: + await self._send(events, channel_name=channel_name, **kwargs) + except Exception as exception: + self._http_response_error_handler(exception, "Basic") + raise exception + + async def _send_binary(self, topic_name: str, events: Any, **kwargs: Any) -> None: + # If data is passed as a dictionary, make sure it is a CloudEvent + try: + if isinstance(events, dict): + events = CloudEvent.from_dict(events) + except AttributeError: + raise TypeError("Binary mode is only supported for type CloudEvent.") # pylint: disable=raise-missing-from + + # If data is a cloud event, convert to an HTTP Request in binary mode + if isinstance(events, CloudEvent): + await self._publish( + topic_name, events, self._config.api_version, **kwargs + ) + else: + raise TypeError("Binary mode is only supported for type CloudEvent.") + + def _http_response_error_handler(self, exception, level): + if isinstance(exception, HttpResponseError): + if exception.status_code == 400: + raise HttpResponseError( + "Invalid event data. Please check the data and try again." + ) from exception + if exception.status_code == 404: + raise ResourceNotFoundError( + "Resource not found. " + f"Please check that the level set on the client, {level}, corresponds to the correct " + "endpoint and/or topic name." + ) from exception + raise exception + + @use_standard_only @distributed_trace_async - async def receive_cloud_events( + async def receive( self, topic_name: str, - event_subscription_name: str, + subscription_name: str, *, max_events: Optional[int] = None, max_wait_time: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> ReceiveResult: """Receive Batch of Cloud Events from the Event Subscription. :param topic_name: Topic Name. Required. :type topic_name: str - :param event_subscription_name: Event Subscription Name. Required. - :type event_subscription_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str :keyword max_events: Max Events count to be received. Minimum value is 1, while maximum value is 100 events. If not specified, the default value is 1. Default value is None. :paramtype max_events: int @@ -236,8 +272,6 @@ async def receive_cloud_events( value is 10 seconds, while maximum value is 120 seconds. If not specified, the default value is 60 seconds. Default value is None. :paramtype max_wait_time: int - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: ReceiveResult. The ReceiveResult is compatible with MutableMapping :rtype: ~azure.eventgrid.models.ReceiveResult :raises ~azure.core.exceptions.HttpResponseError: @@ -246,10 +280,10 @@ async def receive_cloud_events( detail_items = [] receive_result = await self._receive_cloud_events( topic_name, - event_subscription_name, + subscription_name, max_events=max_events, max_wait_time=max_wait_time, - **kwargs + **kwargs, ) for detail_item in receive_result.value: deserialized_cloud_event = CloudEvent.from_dict(detail_item.event) @@ -263,54 +297,193 @@ async def receive_cloud_events( receive_result_deserialized = ReceiveResult(value=detail_items) return receive_result_deserialized - async def _publish(self, topic_name: str, event: Any, api_version, binary_mode, **kwargs: Any) -> None: + @use_standard_only + @distributed_trace_async + async def acknowledge( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + **kwargs: Any, + ) -> _models.AcknowledgeResult: + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + acknowledged lockTokens, along with other failed lockTokens with their corresponding error + information. Successfully acknowledged events will no longer be available to any consumer. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :return: AcknowledgeResult. The AcknowledgeResult is compatible with MutableMapping + :rtype: ~azure.eventgrid.models.AcknowledgeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = AcknowledgeOptions(lock_tokens=lock_tokens) + return await super()._acknowledge_cloud_events( + topic_name, subscription_name, options, **kwargs + ) + + @use_standard_only + @distributed_trace_async + @api_version_validation( + params_added_on={"2023-10-01-preview": ["release_delay_in_seconds"]}, + ) + async def release( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, + **kwargs: Any, + ) -> _models.ReleaseResult: + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released + lockTokens, along with other failed lockTokens with their corresponding error information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay + :return: ReleaseResult. The ReleaseResult is compatible with MutableMapping + :rtype: ~azure.eventgrid.models.ReleaseResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = ReleaseOptions(lock_tokens=lock_tokens) + return await super()._release_cloud_events( + topic_name, + subscription_name, + options, + release_delay_in_seconds=release_delay_in_seconds, + **kwargs, + ) + + @use_standard_only + @distributed_trace_async + async def reject( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + **kwargs: Any, + ) -> _models.RejectResult: + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :return: RejectResult. The RejectResult is compatible with MutableMapping + :rtype: ~azure.eventgrid.models.RejectResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = RejectOptions(lock_tokens=lock_tokens) + return await super()._reject_cloud_events( + topic_name, subscription_name, options, **kwargs + ) + + @use_standard_only + @distributed_trace_async + @api_version_validation( + method_added_on="2023-10-01-preview", + ) + async def renew_locks( + self, + topic_name: str, + subscription_name: str, + *, + lock_tokens: List[str], + **kwargs: Any, + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param subscription_name: Event Subscription Name. Required. + :type subscription_name: str + :keyword lock_tokens: Array of lock tokens of Cloud Events. Required. + :paramtype lock_tokens: List[str] + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + options = RenewLockOptions(lock_tokens=lock_tokens) + return await super()._renew_cloud_event_locks( + topic_name, subscription_name, options, **kwargs + ) + + async def _publish( + self, topic_name: str, event: Any, api_version, **kwargs: Any + ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.PublishResult] = kwargs.pop( # pylint: disable=protected-access - 'cls', None - ) - - content_type: str = kwargs.pop('content_type', _headers.pop('content-type', "application/cloudevents+json; charset=utf-8")) + cls: ClsType[_models._models.PublishResult] = kwargs.pop( + "cls", None + ) # pylint: disable=protected-access + content_type = kwargs.pop("content_type", None) # pylint: disable=unused-variable # Given that we know the cloud event is binary mode, we can convert it to a HTTP request - http_request = _to_http_request( + http_request = _to_http_request( topic_name=topic_name, api_version=api_version, headers=_headers, params=_params, - content_type=content_type, event=event, - binary_mode=binary_mode, - **kwargs + **kwargs, ) _stream = kwargs.pop("stream", False) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) + http_request.url = self._client.format_url( + http_request.url, **path_format_arguments + ) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - http_request, - stream=_stream, - **kwargs + http_request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) + await response.read() # Load the body in memory and close the socket + map_error( + status_code=response.status_code, response=response, error_map=error_map + ) raise HttpResponseError(response=response) if _stream: @@ -318,13 +491,13 @@ async def _publish(self, topic_name: str, event: Any, api_version, binary_mode, else: deserialized = _deserialize( _models._models.PublishResult, # pylint: disable=protected-access - response.json() + response.json(), ) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore __all__: List[str] = [ diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py index 506b7ccced9a..5e8c19f9276d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_patch.py @@ -6,8 +6,83 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import List, Union, Any, TYPE_CHECKING, Optional +from azure.core.credentials import AzureKeyCredential, AzureSasCredential + + from .._legacy.aio import EventGridPublisherClient +from ._client import EventGridClient as InternalEventGridClient +from .._serialization import Deserializer, Serializer +from .._patch import ( + ClientLevel, + DEFAULT_BASIC_API_VERSION, + DEFAULT_STANDARD_API_VERSION, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class EventGridClient(InternalEventGridClient): + """Azure Messaging EventGrid Client. + + :param endpoint: The endpoint to the Event Grid resource. + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.AzureSasCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value for namespaces is + "2023-10-01-preview". Default value for basic is "2018-01-01". Note that overriding this default value may result in unsupported + behavior. + :paramtype api_version: str or None + :keyword level: The level of client to use. + Known values include: "Basic", "Standard". Default value is "Standard". + `Standard` is used for working with a namespace topic. + `Basic` is used for working with a basic topic. + :paramtype level: str + """ + + def __init__( + self, + endpoint: str, + credential: Union[ + AzureKeyCredential, AzureSasCredential, "AsyncTokenCredential" + ], + *, + api_version: Optional[str] = None, + level: Union[str, ClientLevel] = "Standard", + **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._level = level + + if level == ClientLevel.BASIC: + self._client = EventGridPublisherClient( # type: ignore[assignment] + endpoint, + credential, + api_version=api_version or DEFAULT_BASIC_API_VERSION, + **kwargs + ) + self._send = self._client.send # type: ignore[attr-defined] + elif level == ClientLevel.STANDARD: + if isinstance(credential, AzureSasCredential): + raise TypeError( + "SAS token authentication is not supported for the standard client." + ) + + super().__init__( + endpoint=endpoint, + credential=credential, + api_version=api_version or DEFAULT_STANDARD_API_VERSION, + **kwargs + ) + self._send = self._publish_cloud_events + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + def patch_sdk(): """Do not remove from this file. @@ -18,5 +93,6 @@ def patch_sdk(): __all__: List[str] = [ + "EventGridClient", "EventGridPublisherClient", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py index 7d7d97b1ac12..2bf8ba7809c7 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py @@ -6,34 +6,22 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._models import AcknowledgeOptions from ._models import AcknowledgeResult -from ._models import Error from ._models import FailedLockToken -from ._models import InnerError -from ._models import RejectOptions from ._models import RejectResult -from ._models import ReleaseOptions from ._models import ReleaseResult from ._models import RenewCloudEventLocksResult -from ._models import RenewLockOptions from ._enums import ReleaseDelay from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'AcknowledgeOptions', 'AcknowledgeResult', - 'Error', 'FailedLockToken', - 'InnerError', - 'RejectOptions', 'RejectResult', - 'ReleaseOptions', 'ReleaseResult', 'RenewCloudEventLocksResult', - 'RenewLockOptions', 'ReleaseDelay', ] __all__.extend([p for p in _patch_all if p not in __all__]) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py index a9bcc960fafc..c7fb2c8270fa 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py @@ -31,24 +31,6 @@ class AcknowledgeOptions(_model_base.Model): """Array of lock tokens. Required.""" - @overload - def __init__( - self, - *, - lock_tokens: List[str], - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - @@ -198,34 +180,12 @@ class Error(_model_base.Model): """A human-readable representation of the error. Required.""" target: Optional[str] = rest_field() """The target of the error.""" - details: Optional[List["_models.Error"]] = rest_field() + details: Optional[List["_models._models.Error"]] = rest_field() """An array of details about specific errors that led to this reported error.""" - innererror: Optional["_models.InnerError"] = rest_field() + innererror: Optional["_models._models.InnerError"] = rest_field() """An object containing more specific information than the current object about the error.""" - @overload - def __init__( - self, - *, - code: str, - message: str, - target: Optional[str] = None, - details: Optional[List["_models.Error"]] = None, - innererror: Optional["_models.InnerError"] = None, - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - @@ -243,7 +203,7 @@ class FailedLockToken(_model_base.Model): lock_token: str = rest_field(name="lockToken") """The lock token of an entry in the request. Required.""" - error: "_models.Error" = rest_field() + error: "_models._models.Error" = rest_field() """Error information of the failed operation result for the lock token in the request. Required.""" @@ -252,7 +212,7 @@ def __init__( self, *, lock_token: str, - error: "_models.Error", + error: "_models._models.Error", ): ... @@ -282,29 +242,10 @@ class InnerError(_model_base.Model): code: Optional[str] = rest_field() """One of a server-defined set of error codes.""" - innererror: Optional["_models.InnerError"] = rest_field() + innererror: Optional["_models._models.InnerError"] = rest_field() """Inner error.""" - @overload - def __init__( - self, - *, - code: Optional[str] = None, - innererror: Optional["_models.InnerError"] = None, - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - @@ -367,24 +308,6 @@ class RejectOptions(_model_base.Model): """Array of lock tokens. Required.""" - @overload - def __init__( - self, - *, - lock_tokens: List[str], - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - @@ -444,24 +367,6 @@ class ReleaseOptions(_model_base.Model): """Array of lock tokens. Required.""" - @overload - def __init__( - self, - *, - lock_tokens: List[str], - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - @@ -563,22 +468,4 @@ class RenewLockOptions(_model_base.Model): """Array of lock tokens. Required.""" - @overload - def __init__( - self, - *, - lock_tokens: List[str], - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py index ff93f72c6f87..ee8fa6387b70 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_patch.py @@ -8,13 +8,13 @@ """ from typing import List, overload, Mapping, Any from azure.core.messaging import CloudEvent -from .. import _model_base from ._models import ( ReceiveDetails as InternalReceiveDetails, ReceiveResult as InternalReceiveResult, BrokerProperties as InternalBrokerProperties, ) + class ReceiveDetails(InternalReceiveDetails): """Receive operation details per Cloud Event. @@ -32,8 +32,7 @@ def __init__( *, broker_properties: "BrokerProperties", event: "CloudEvent", - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -42,9 +41,9 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__( + def __init__( # pylint: disable=useless-super-delegation self, *args: Any, **kwargs: Any - ) -> None: # pylint: disable=useless-super-delegation + ) -> None: super().__init__(*args, **kwargs) @@ -62,8 +61,7 @@ def __init__( self, *, value: List["ReceiveDetails"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -72,9 +70,9 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__( + def __init__( # pylint: disable=useless-super-delegation self, *args: Any, **kwargs: Any - ) -> None: # pylint: disable=useless-super-delegation + ) -> None: super().__init__(*args, **kwargs) @@ -95,8 +93,7 @@ def __init__( *, lock_token: str, delivery_count: int, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -105,9 +102,9 @@ def __init__(self, mapping: Mapping[str, Any]): :type mapping: Mapping[str, Any] """ - def __init__( + def __init__( # pylint: disable=useless-super-delegation self, *args: Any, **kwargs: Any - ) -> None: # pylint: disable=useless-super-delegation + ) -> None: super().__init__(*args, **kwargs) diff --git a/sdk/eventgrid/azure-eventgrid/samples/README.md b/sdk/eventgrid/azure-eventgrid/samples/README.md index fff007e9966e..4a456ff13937 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/README.md +++ b/sdk/eventgrid/azure-eventgrid/samples/README.md @@ -10,7 +10,30 @@ urlFragment: eventgrid-samples # Azure Event Grid Client Library Python Samples -## Sync samples +## Namespace Sync samples +These code samples show common champion scenario operations with the Azure Event Grid client library. + +* Authenticate the client: [sample_authentication.py][python-eg-auth] +* Publish events to a namespace topic:[sample_publish_operation.py][python-eg-client-publish-sample] +* Publish events in binary mode to a namespace topic: [sample_binary_mode.py][python-eg-client-binary-mode-sample] +* Receive events from a namespace topic: [sample_receive_operation.py][python-eg-client-receive-sample] +* Acknowledge events from a namespace topic: [sample_acknowledge_operation.py][python-eg-client-ack-sample] +* Release events from a namespace topic: [sample_release_operation.py][python-eg-client-release-sample] +* Reject events from a namespace topic: [sample_reject_operation.py][python-eg-client-reject-sample] +* Renew locks: [sample_renew_locks_operation.py][python-eg-client-renew-locks-sample] + +## Namespace Async samples + +* Publish events to a namespace topic:[sample_publish_operation_async.py][python-eg-client-publish-sample-async] +* Publish events in binary mode to a namespace topic: [sample_binary_mode_async.py][python-eg-client-binary-mode-sample-async] +* Receive events from a namespace topic: [sample_receive_operation_async.py][python-eg-client-receive-sample-async] +* Acknowledge events from a namespace topic: [sample_acknowledge_operation_async.py][python-eg-client-ack-sample-async] +* Release events from a namespace topic: [sample_release_operation_async.py][python-eg-client-release-sample-async] +* Reject events from a namespace topic: [sample_reject_operation_async.py][python-eg-client-reject-sample-async] +* Renew locks: [sample_renew_locks_operation_async.py][python-eg-client-renew-locks-sample-async] + + +## Basic Sync samples These code samples show common champion scenario operations with the Azure Event Grid client library. * Generate Shared Access Signature: [sample_generate_sas.py][python-eg-generate-sas] @@ -29,9 +52,7 @@ To publish events, dict representation of the models could also be used as follo * Consume a Custom Payload of raw cloudevent data: [sample_consume_custom_payload.py][python-eg-sample-consume-custom-payload] -EventGridClient operation samples: [EventGridClient samples][python-eg-client-sync-samples] - -## Async samples +## Basic Async samples These code samples show common champion scenario operations with the Azure Event Grid client library using the async client. * Authenticate the client: [sample_authentication_async.py][python-eg-auth-async] @@ -46,8 +67,6 @@ To publish events, dict representation of the models could also be used as follo * Publish EventGridEvent as dict like representation: [sample_publish_eg_event_using_dict_async.py][python-eg-sample-send-eg-as-dict-async] * Publish CloudEvent as dict like representation: [sample_publish_cloud_event_using_dict_async.py][python-eg-sample-send-cloudevent-as-dict-async] -EventGridClient operation samples: [EventGridClient samples][python-eg-client-async-samples] - ## More Samples * More samples related to the send scenario can be seen [here][python-eg-publish-samples]. @@ -80,4 +99,47 @@ EventGridClient operation samples: [EventGridClient samples][python-eg-client-as [publisher-service-doc]: https://docs.microsoft.com/azure/event-grid/concepts [python-eg-client-sync-samples]: https://github.com/Azure/azure-sdk-for-python/tree/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples -[python-eg-client-async-samples]:https://github.com/Azure/azure-sdk-for-python/tree/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples \ No newline at end of file +[python-eg-client-async-samples]:https://github.com/Azure/azure-sdk-for-python/tree/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples + +[python-eg-client-ack-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py + +[python-eg-client-all-ops-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py + +[python-eg-client-binary-mode-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py + +[python-eg-client-publish-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_operation.py + +[python-eg-client-receive-renew-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py + +[python-eg-client-release-receive-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py + +[python-eg-client-receive-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py + +[python-eg-client-release-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py + + +[python-eg-client-reject-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py + +[python-eg-client-renew-locks-sample]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py + + +[python-eg-client-ack-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py + +[python-eg-client-all-ops-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py + +[python-eg-client-binary-mode-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py + +[python-eg-client-publish-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py + +[python-eg-client-receive-renew-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py + +[python-eg-client-release-receive-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py + +[python-eg-client-receive-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py + +[python-eg-client-release-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py + + +[python-eg-client-reject-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py + +[python-eg-client-renew-locks-sample-async]:https://github.com/Azure/azure-sdk-for-python/blob/feature/eventgrid/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py index bc53812fa804..acbde2f1e706 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_acknowledge_operation_async.py +DESCRIPTION: + These samples demonstrate acknowledging CloudEvent lock tokens. +USAGE: + python sample_acknowledge_operation_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -23,11 +36,11 @@ async def run(): # Acknowledge a batch of CloudEvents try: async with client: - lock_tokens = AcknowledgeOptions(lock_tokens=["token"]) - ack_events = await client.acknowledge_cloud_events( + lock_tokens = ["token"] + ack_events = await client.acknowledge( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - acknowledge_options=lock_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens, ) print(ack_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py index d31666095998..ac862916ab27 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_all_operations_async.py +DESCRIPTION: + These samples demonstrate sending, receiving, acknowledging, and releasing CloudEvents. +USAGE: + python sample_all_operations_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -36,8 +49,8 @@ async def run(): async with client: # Publish a CloudEvent try: - await client.publish_cloud_events( - topic_name=TOPIC_NAME, body=cloud_event_reject + await client.send( + topic_name=TOPIC_NAME, events=cloud_event_reject ) except HttpResponseError: raise @@ -45,17 +58,17 @@ async def run(): # Publish a list of CloudEvents try: list_of_cloud_events = [cloud_event_release, cloud_event_ack] - await client.publish_cloud_events( - topic_name=TOPIC_NAME, body=list_of_cloud_events + await client.send( + topic_name=TOPIC_NAME, events=list_of_cloud_events ) except HttpResponseError: raise # Receive Published Cloud Events try: - receive_results = await client.receive_cloud_events( + receive_results = await client.receive( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10, ) @@ -82,11 +95,10 @@ async def run(): if len(release_events) > 0: try: - release_tokens = ReleaseOptions(lock_tokens=release_events) - release_result = await client.release_cloud_events( + release_result = await client.release( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - release_options=release_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=release_events, ) except HttpResponseError: raise @@ -96,11 +108,10 @@ async def run(): if len(acknowledge_events) > 0: try: - ack_tokens = AcknowledgeOptions(lock_tokens=acknowledge_events) - ack_result = await client.acknowledge_cloud_events( + ack_result = await client.acknowledge( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - acknowledge_options=ack_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=acknowledge_events, ) except HttpResponseError: raise @@ -110,11 +121,10 @@ async def run(): if len(reject_events) > 0: try: - reject_tokens = RejectOptions(lock_tokens=reject_events) - reject_result = await client.reject_cloud_events( + reject_result = await client.reject( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - reject_options=reject_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=reject_events, ) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py index 6b50f1fe9444..3e9d918cd15c 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_binary_mode_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_binary_mode_async.py +DESCRIPTION: + These samples demonstrate sending CloudEvents in binary mode. +USAGE: + python sample_binary_mode_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio import json @@ -28,15 +41,15 @@ async def run(): try: # Publish CloudEvent in binary mode with str encoded as bytes cloud_event_dict = {"data":b"HI", "source":"https://example.com", "type":"example", "datacontenttype":"text/plain"} - await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event_dict, binary_mode=True) + await client.send(topic_name=TOPIC_NAME, events=cloud_event_dict, binary_mode=True) # Publish CloudEvent in binary mode with json encoded as bytes cloud_event = CloudEvent(data=json.dumps({"hello":"data"}).encode("utf-8"), source="https://example.com", type="example", datacontenttype="application/json") - await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event, binary_mode=True) + await client.send(topic_name=TOPIC_NAME, events=cloud_event, binary_mode=True) - receive_result = await client.receive_cloud_events( + receive_result = await client.receive( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10, ) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py index 5fd2486723a6..aae84b550ecc 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_operation_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_publish_operation_async.py +DESCRIPTION: + These samples demonstrate sending CloudEvents. +USAGE: + python sample_publish_operation_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -27,13 +40,13 @@ async def run(): # Publish a CloudEvent as dict try: cloud_event_dict = {"data": "hello", "source": "https://example.com", "type": "example"} - await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event_dict) + await client.send(topic_name=TOPIC_NAME, events=cloud_event_dict) except HttpResponseError: raise # Publish a list of CloudEvents as dict try: - await client.publish_cloud_events(topic_name=TOPIC_NAME, body=[cloud_event_dict, cloud_event_dict]) + await client.send(topic_name=TOPIC_NAME, events=[cloud_event_dict, cloud_event_dict]) except HttpResponseError: raise @@ -43,15 +56,15 @@ async def run(): cloud_event = CloudEvent( data="HI", source="https://example.com", type="example" ) - await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + await client.send(topic_name=TOPIC_NAME, events=cloud_event) except HttpResponseError: raise # Publish a list of CloudEvents try: list_of_cloud_events = [cloud_event, cloud_event] - await client.publish_cloud_events( - topic_name=TOPIC_NAME, body=list_of_cloud_events + await client.send( + topic_name=TOPIC_NAME, events=list_of_cloud_events ) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py index 62d02f707f80..020b830b6e5e 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_publish_receive_renew_async.py +DESCRIPTION: + These samples demonstrate sending, receiving, and renewing CloudEvents. +USAGE: + python sample_publish_receive_renew_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -26,20 +39,19 @@ async def run(): try: # Publish a CloudEvent cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") - await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + await client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) + receive_result = await client.receive(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) lock_tokens_to_release = [] for item in receive_result.value: lock_tokens_to_release.append(item.broker_properties.lock_token) # Renew lock tokens - lock_tokens = RenewLockOptions(lock_tokens=lock_tokens_to_release) - renew_events = await client.renew_cloud_event_locks( + renew_events = await client.renew_locks( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - renew_lock_options=lock_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens_to_release, ) print("Renewed Event:", renew_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py index 895640a9d8f6..d1b5d0c6bbe3 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_publish_release_receive_async.py +DESCRIPTION: + These samples demonstrate sending, receiving, and releasing CloudEvents. +USAGE: + python sample_publish_release_receive_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -26,10 +39,10 @@ async def run(): try: # Publish a CloudEvent cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") - await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + await client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = await client.receive(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) lock_tokens_to_release = [] for item in receive_result.value: lock_tokens_to_release.append(item.broker_properties.lock_token) @@ -37,25 +50,23 @@ async def run(): print("Received events:", receive_result.value) # Release a LockToken - release_token = ReleaseOptions(lock_tokens=lock_tokens_to_release) - release_events = await client.release_cloud_events( + release_events = await client.release( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, release_delay_in_seconds=60, - release_options=release_token, + lock_tokens=lock_tokens_to_release, ) print("Released Event:", release_events) # Receive CloudEvents again - receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = await client.receive(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) print("Received events after release:", receive_result.value) - # Acknowledge LockTokens - acknowledge_token = AcknowledgeOptions(lock_tokens=lock_tokens_to_release) - acknowledge_events = await client.acknowledge_cloud_events( + # Acknowledge a LockToken that was released + acknowledge_events = await client.acknowledge( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - acknowledge_options=acknowledge_token, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens_to_release, ) print("Acknowledged events after release:", acknowledge_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py index 6d136c5ff5e4..c166adc49d84 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_receive_operation_async.py +DESCRIPTION: + These samples demonstrate receiving CloudEvents. +USAGE: + python sample_receive_operations_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -23,9 +36,9 @@ async def run(): # Receive CloudEvents try: async with client: - receive_result = await client.receive_cloud_events( + receive_result = await client.receive( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10, ) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py index c1ea4b70c3dd..c8ccc0c30a6c 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_reject_operation_async.py +DESCRIPTION: + These samples demonstrate rejecting CloudEvents. +USAGE: + python sample_reject_operation_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -23,11 +36,11 @@ async def run(): # Reject a LockToken try: async with client: - tokens = RejectOptions(lock_tokens=["token"]) - reject_events = await client.reject_cloud_events( + tokens = ["token"] + reject_events = await client.reject( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - reject_options=tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=tokens, ) print(reject_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py index 0ef5fc8dd4ab..cdb308dd6aac 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_release_operation_async.py +DESCRIPTION: + These samples demonstrate releasing CloudEvents. +USAGE: + python sample_release_operation_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -23,12 +36,12 @@ async def run(): # Release a LockToken try: async with client: - tokens = ReleaseOptions(lock_tokens=["token"]) - release_events = await client.release_cloud_events( + tokens = ["token"] + release_events = await client.release( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, release_delay_in_seconds=10, - release_options=tokens, + lock_tokens=tokens, ) print(release_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py index 89938ee40978..09e672fc9661 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_renew_locks_operation_async.py +DESCRIPTION: + These samples demonstrate renewing CloudEvents locks. +USAGE: + python sample_renew_locks_operation_async.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -21,11 +34,11 @@ async def run(): # Renew a lockToken try: - lock_tokens = RenewLockOptions(lock_tokens=["token"]) - release_events = await client.renew_cloud_event_locks( + lock_tokens = ["token"] + release_events = await client.renew_locks( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - renew_lock_options=lock_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens, ) print(release_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_authentication_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_authentication_async.py index a26411bb95ed..54075cdbf128 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_authentication_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_authentication_async.py @@ -17,31 +17,31 @@ """ # [START client_auth_with_key_cred_async] import os -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential topic_key = os.environ["EVENTGRID_TOPIC_KEY"] endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] credential_key = AzureKeyCredential(topic_key) -client = EventGridPublisherClient(endpoint, credential_key) +client = EventGridClient(endpoint, credential_key, level="Basic") # [END client_auth_with_key_cred_async] # [START client_auth_with_sas_cred_async] import os -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureSasCredential signature = os.environ["EVENTGRID_SAS"] endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] credential_sas = AzureSasCredential(signature) -client = EventGridPublisherClient(endpoint, credential_sas) +client = EventGridClient(endpoint, credential_sas, level="Basic") # [END client_auth_with_sas_cred_async] # [START client_auth_with_token_cred_async] from azure.identity.aio import DefaultAzureCredential -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.eventgrid import EventGridEvent event = EventGridEvent( @@ -53,5 +53,5 @@ default_az_credential = DefaultAzureCredential() endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] -client = EventGridPublisherClient(endpoint, default_az_credential) +client = EventGridClient(endpoint, default_az_credential, level="Basic") # [END client_auth_with_token_cred_async] diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cloud_event_using_dict_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cloud_event_using_dict_async.py index d6737c21420d..5e2be47c8c7c 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cloud_event_using_dict_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cloud_event_using_dict_async.py @@ -18,7 +18,7 @@ import os import asyncio from azure.core.messaging import CloudEvent -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential topic_key = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_KEY"] @@ -27,7 +27,7 @@ async def publish(): credential = AzureKeyCredential(topic_key) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") # [START publish_cloud_event_dict_async] async with client: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cncf_cloud_events_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cncf_cloud_events_async.py index f755c9724c46..a72484e27301 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cncf_cloud_events_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_cncf_cloud_events_async.py @@ -16,7 +16,7 @@ """ import os import asyncio -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential from cloudevents.http import CloudEvent @@ -26,19 +26,20 @@ async def publish(): credential = AzureKeyCredential(topic_key) - client = EventGridPublisherClient(endpoint, credential) - await client.send( - [ - CloudEvent( - attributes={ - "type": "cloudevent", - "source": "/cncf/cloud/event/1.0", - "subject": "testing-cncf-event", - }, - data=b"This is a cncf cloud event.", - ) - ] - ) + client = EventGridClient(endpoint, credential, level="Basic") + async with client: + await client.send( + [ + CloudEvent( + attributes={ + "type": "cloudevent", + "source": "/cncf/cloud/event/1.0", + "subject": "testing-cncf-event", + }, + data=b"This is a cncf cloud event.", + ) + ] + ) if __name__ == "__main__": diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_custom_schema_to_a_topic_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_custom_schema_to_a_topic_async.py index 2d7ccbb8cbcf..40f268f84112 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_custom_schema_to_a_topic_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_custom_schema_to_a_topic_async.py @@ -23,7 +23,7 @@ import datetime as dt from azure.core.credentials import AzureKeyCredential -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient key = os.environ["EVENTGRID_CUSTOM_EVENT_TOPIC_KEY"] endpoint = os.environ["EVENTGRID_CUSTOM_EVENT_TOPIC_ENDPOINT"] @@ -33,7 +33,7 @@ async def publish_event(): # authenticate client # [START publish_custom_schema_async] credential = AzureKeyCredential(key) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") custom_schema_event = { "customSubject": "sample", diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_event_using_dict_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_event_using_dict_async.py index 8909b5717b2b..605c0b3f5236 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_event_using_dict_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_event_using_dict_async.py @@ -20,7 +20,7 @@ import asyncio from datetime import datetime from azure.eventgrid import EventGridEvent -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential topic_key = os.environ["EVENTGRID_TOPIC_KEY"] @@ -29,7 +29,7 @@ async def publish(): credential = AzureKeyCredential(topic_key) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") # [START publish_eg_event_dict_async] event0 = { diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_domain_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_domain_async.py index 48272cb30166..ace029405cda 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_domain_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_domain_async.py @@ -18,7 +18,7 @@ import os import asyncio from azure.eventgrid import EventGridEvent -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential domain_key = os.environ["EVENTGRID_DOMAIN_KEY"] @@ -27,26 +27,26 @@ async def publish(): credential = AzureKeyCredential(domain_key) - client = EventGridPublisherClient(domain_hostname, credential) - - await 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", - ), - ] - ) + client = EventGridClient(domain_hostname, credential, level="Basic") + async with client: + await 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", + ), + ] + ) if __name__ == "__main__": diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_topic_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_topic_async.py index 4ab76f2a81fa..8628477492ce 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_topic_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_eg_events_to_a_topic_async.py @@ -18,7 +18,7 @@ import os import asyncio from azure.eventgrid import EventGridEvent -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential topic_key = os.environ["EVENTGRID_TOPIC_KEY"] @@ -27,18 +27,18 @@ async def publish(): credential = AzureKeyCredential(topic_key) - client = EventGridPublisherClient(endpoint, credential) - - await client.send( - [ - EventGridEvent( - event_type="Contoso.Items.ItemReceived", - data={"itemSku": "Contoso Item SKU #1"}, - subject="Door1", - data_version="2.0", - ) - ] - ) + client = EventGridClient(endpoint, credential, level="Basic") + async with client: + await client.send( + [ + EventGridEvent( + event_type="Contoso.Items.ItemReceived", + data={"itemSku": "Contoso Item SKU #1"}, + subject="Door1", + data_version="2.0", + ) + ] + ) # [END publish_eg_event_to_topic_async] diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_to_a_topic_using_sas_credential_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_to_a_topic_using_sas_credential_async.py index c70bfd11aef4..d56ce6c5f265 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_to_a_topic_using_sas_credential_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_to_a_topic_using_sas_credential_async.py @@ -17,7 +17,7 @@ import os import asyncio from azure.eventgrid import EventGridEvent -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureSasCredential sas = os.environ["EVENTGRID_SAS"] @@ -26,7 +26,7 @@ async def publish(): credential = AzureSasCredential(sas) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") async with client: await client.send( diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_using_cloud_events_1.0_schema_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_using_cloud_events_1.0_schema_async.py index 1d3ea0337e33..93f953a7ba9b 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_using_cloud_events_1.0_schema_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_events_using_cloud_events_1.0_schema_async.py @@ -18,7 +18,7 @@ import os import asyncio from azure.core.messaging import CloudEvent -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential topic_key = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_KEY"] @@ -27,18 +27,18 @@ async def publish(): credential = AzureKeyCredential(topic_key) - client = EventGridPublisherClient(endpoint, credential) - - await client.send( - [ - CloudEvent( - type="Contoso.Items.ItemReceived", - source="/contoso/items", - data={"itemSku": "Contoso Item SKU #1"}, - subject="Door1", - ) - ] - ) + client = EventGridClient(endpoint, credential, level="Basic") + async with client: + await client.send( + [ + CloudEvent( + type="Contoso.Items.ItemReceived", + source="/contoso/items", + data={"itemSku": "Contoso Item SKU #1"}, + subject="Door1", + ) + ] + ) # [END publish_cloud_event_to_topic_async] diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_to_channel_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_to_channel_async.py index f12070c35a1e..8cf418b53207 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_to_channel_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/sample_publish_to_channel_async.py @@ -18,7 +18,7 @@ # [START publish_cloud_event_to_topic] import os import asyncio -from azure.eventgrid.aio import EventGridPublisherClient +from azure.eventgrid.aio import EventGridClient from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent @@ -30,7 +30,7 @@ async def publish(): credential = AzureKeyCredential(topic_key) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") async with client: await client.send( [ diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py index bb6b7420cef1..9a04a87df6d9 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_custom_topic_sample.py @@ -21,14 +21,14 @@ from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient key = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_KEY"] endpoint = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT"] # authenticate client credential = AzureKeyCredential(key) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level="Basic") services = [ "EventGrid", diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py index b12784c078b7..d30969af523b 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_cloud_events_to_domain_topic_sample.py @@ -22,7 +22,7 @@ from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient domain_key = os.environ["EVENTGRID_CLOUD_EVENT_DOMAIN_KEY"] domain_endpoint = os.environ["EVENTGRID_CLOUD_EVENT_DOMAIN_ENDPOINT"] @@ -30,7 +30,7 @@ # authenticate client credential = AzureKeyCredential(domain_key) -client = EventGridPublisherClient(domain_endpoint, credential) +client = EventGridClient(domain_endpoint, credential, level="Basic") def publish_event(): diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_custom_schema_events_to_topic_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_custom_schema_events_to_topic_sample.py index 4f51f1b6990c..8a25456e45cb 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_custom_schema_events_to_topic_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_custom_schema_events_to_topic_sample.py @@ -22,7 +22,7 @@ import datetime as dt from azure.core.credentials import AzureKeyCredential -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient key = os.environ["EVENTGRID_CUSTOM_EVENT_TOPIC_KEY"] endpoint = os.environ["EVENTGRID_CUSTOM_EVENT_TOPIC_ENDPOINT"] @@ -31,7 +31,7 @@ def publish_event(): # authenticate client credential = AzureKeyCredential(key) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") custom_schema_event = { "customSubject": "sample", diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py index 075dc12fdfdf..1f00e36dcf18 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_event_grid_events_to_custom_topic_sample.py @@ -20,14 +20,14 @@ import time from azure.core.credentials import AzureKeyCredential -from azure.eventgrid import EventGridPublisherClient, EventGridEvent +from azure.eventgrid import EventGridClient, EventGridEvent key = os.environ["EVENTGRID_TOPIC_KEY"] endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] # authenticate client credential = AzureKeyCredential(key) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level="Basic") services = [ "EventGrid", "ServiceBus", diff --git a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py index dea31e7b7ae0..4afdeebc182b 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py +++ b/sdk/eventgrid/azure-eventgrid/samples/publish_samples/publish_with_shared_access_signature_sample.py @@ -22,7 +22,7 @@ from datetime import datetime, timedelta from azure.core.credentials import AzureSasCredential from azure.core.messaging import CloudEvent -from azure.eventgrid import EventGridPublisherClient, generate_sas +from azure.eventgrid import EventGridClient, generate_sas key = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_KEY"] endpoint = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT"] @@ -32,7 +32,7 @@ # authenticate client credential = AzureSasCredential(signature) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level="Basic") services = [ "EventGrid", diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py deleted file mode 100644 index 780c9cc975e2..000000000000 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py +++ /dev/null @@ -1,14 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import os -from azure.eventgrid import EventGridClient -from azure.eventgrid.models import * -from azure.identity import DefaultAzureCredential - -EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] - -# Create a client using DefaultAzureCredential -client = EventGridClient(EVENTGRID_ENDPOINT, DefaultAzureCredential()) \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py index 72a5518c6228..c7c2df51bed1 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_acknowledge_operation.py +DESCRIPTION: + These samples demonstrate acknowledging CloudEvents. +USAGE: + python sample_acknowledge_operation.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -20,11 +33,11 @@ # Acknowledge a CloudEvent try: - lock_tokens = AcknowledgeOptions(lock_tokens=["token"]) - ack_events = client.acknowledge_cloud_events( + lock_tokens = ["token"] + ack_events = client.acknowledge( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - acknowledge_options=lock_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens, ) print(ack_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py index 52d12730c41d..2299988e0b4c 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_all_operations.py +DESCRIPTION: + These samples demonstrate sending, receiving, releasing, and acknowledging CloudEvents. +USAGE: + python sample_all_operations.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import asyncio from azure.core.credentials import AzureKeyCredential @@ -33,22 +46,22 @@ # Publish a CloudEvent try: - client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event_reject) + client.send(topic_name=TOPIC_NAME, events=cloud_event_reject) except HttpResponseError: raise # Publish a list of CloudEvents try: list_of_cloud_events = [cloud_event_release, cloud_event_ack] - client.publish_cloud_events(topic_name=TOPIC_NAME, body=list_of_cloud_events) + client.send(topic_name=TOPIC_NAME, events=list_of_cloud_events) except HttpResponseError: raise # Receive Published Cloud Events try: - receive_results = client.receive_cloud_events( + receive_results = client.receive( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10, ) @@ -75,11 +88,10 @@ if len(release_events) > 0: try: - release_tokens = ReleaseOptions(lock_tokens=release_events) - release_result = client.release_cloud_events( + release_result = client.release( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - release_options=release_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=release_events, ) except HttpResponseError: raise @@ -89,11 +101,10 @@ if len(acknowledge_events) > 0: try: - ack_tokens = AcknowledgeOptions(lock_tokens=acknowledge_events) - ack_result = client.acknowledge_cloud_events( + ack_result = client.acknowledge( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - acknowledge_options=ack_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=acknowledge_events, ) except HttpResponseError: raise @@ -103,11 +114,10 @@ if len(reject_events) > 0: try: - reject_tokens = RejectOptions(lock_tokens=reject_events) - reject_result = client.reject_cloud_events( + reject_result = client.reject( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - reject_options=reject_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=reject_events, ) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py index 45240b174a8c..884c9adfbd15 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_binary_mode.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_binary_mode.py +DESCRIPTION: + These samples demonstrate sending CloudEvents in binary mode. +USAGE: + python sample_binary_mode.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os import json from azure.core.credentials import AzureKeyCredential @@ -25,14 +38,14 @@ try: # Publish CloudEvent in binary mode with str encoded as bytes cloud_event_dict = {"data":b"HI", "source":"https://example.com", "type":"example", "datacontenttype":"text/plain"} - client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event_dict, binary_mode=True) + client.send(topic_name=TOPIC_NAME, events=cloud_event_dict, binary_mode=True) # Publish CloudEvent in binary mode with json encoded as bytes cloud_event = CloudEvent(data=json.dumps({"hello":"data"}).encode("utf-8"), source="https://example.com", type="example", datacontenttype="application/json") - client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event, binary_mode=True) + client.send(topic_name=TOPIC_NAME, events=cloud_event, binary_mode=True) # Receive a CloudEvent - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=100) + receive_result = client.receive(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=100) for receive_details in receive_result.value: cloud_event_received = receive_details.event print("CloudEvent: ", cloud_event_received) diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_eg_client_authentication.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_eg_client_authentication.py deleted file mode 100644 index a95d1613c823..000000000000 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_eg_client_authentication.py +++ /dev/null @@ -1,27 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -""" -FILE: sample_eg_client_authentication.py -DESCRIPTION: - These samples demonstrate authenticating an EventGridClient. -USAGE: - python sample_eg_client_authentication.py - Set the environment variables with your own values before running the sample: - 1) EVENTGRID_KEY - The access key of your eventgrid account. - 2) EVENTGRID_ENDPOINT - The namespace hostname. Typically it exists in the format - "https://..eventgrid.azure.net". -""" -# [START client_auth_with_key_cred] -import os -from azure.eventgrid import EventGridClient -from azure.core.credentials import AzureKeyCredential - -key: str = os.environ["EVENTGRID_KEY"] -endpoint: str = os.environ["EVENTGRID_ENDPOINT"] - -credential = AzureKeyCredential(key) -client = EventGridClient(endpoint, credential) -# [END client_auth_with_key_cred] diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_operation.py index 3c4db3a37f3b..d6ce90dee42b 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_operation.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_publish_operation.py +DESCRIPTION: + These samples demonstrate sending CloudEvents. +USAGE: + python sample_publish_operation.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -22,26 +35,26 @@ # Publish a CloudEvent as dict try: cloud_event_dict = {"data": "hello", "source": "https://example.com", "type": "example"} - client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event_dict) + client.send(topic_name=TOPIC_NAME, events=cloud_event_dict) except HttpResponseError: raise # Publish a list of CloudEvents as dict try: - client.publish_cloud_events(topic_name=TOPIC_NAME, body=[cloud_event_dict, cloud_event_dict]) + client.send(topic_name=TOPIC_NAME, events=[cloud_event_dict, cloud_event_dict]) except HttpResponseError: raise # Publish a CloudEvent try: cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") - client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + client.send(topic_name=TOPIC_NAME, events=cloud_event) except HttpResponseError: raise # Publish a list of CloudEvents try: list_of_cloud_events = [cloud_event, cloud_event] - client.publish_cloud_events(topic_name=TOPIC_NAME, body=list_of_cloud_events) + client.send(topic_name=TOPIC_NAME, events=list_of_cloud_events) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py index 38492b231d7b..1db143b432f9 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_publish_receive_renew.py +DESCRIPTION: + These samples demonstrate sending, receiving and renewing CloudEvents. +USAGE: + python sample_publish_receive_renew.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -23,20 +36,19 @@ try: # Publish a CloudEvent cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") - client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) - lock_tokens_to_release = [] + receive_result = client.receive(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) + lock_tokens_to_renew = [] for item in receive_result.value: - lock_tokens_to_release.append(item.broker_properties.lock_token) + lock_tokens_to_renew.append(item.broker_properties.lock_token) # Renew a lock token - lock_tokens = RenewLockOptions(lock_tokens=lock_tokens_to_release) - renew_events = client.renew_cloud_event_locks( + renew_events = client.renew_locks( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - renew_lock_options=lock_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens_to_renew, ) print("Renewed Event:", renew_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py index ef97375c3f0b..ed357aa1ad52 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_publish_release_receive.py +DESCRIPTION: + These samples demonstrate sending, receiving and releasing CloudEvents. +USAGE: + python sample_publish_release_receive.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -23,10 +36,10 @@ try: # Publish a CloudEvent cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") - client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + client.send(topic_name=TOPIC_NAME, events=cloud_event) # Receive CloudEvents and parse out lock tokens - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = client.receive(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) lock_tokens_to_release = [] for item in receive_result.value: lock_tokens_to_release.append(item.broker_properties.lock_token) @@ -34,25 +47,23 @@ print("Received events:", receive_result.value) # Release a LockToken - release_token = ReleaseOptions(lock_tokens=lock_tokens_to_release) - release_events = client.release_cloud_events( + release_events = client.release( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, release_delay_in_seconds=60, - release_options=release_token, + lock_tokens=lock_tokens_to_release, ) print("Released Event:", release_events) # Receive CloudEvents again - receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + receive_result = client.receive(topic_name=TOPIC_NAME, subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) print("Received events after release:", receive_result.value) - # Acknowledge a LockToken - acknowledge_token = AcknowledgeOptions(lock_tokens=lock_tokens_to_release) - acknowledge_events = client.acknowledge_cloud_events( + # Acknowledge a LockToken that was released + acknowledge_events = client.acknowledge( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - acknowledge_options=acknowledge_token, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens_to_release, ) print("Acknowledged events after release:", acknowledge_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py index 20252bda9cac..4e7c69bcec7b 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_receive_operation.py +DESCRIPTION: + These samples demonstrate receiving CloudEvents. +USAGE: + python sample_receive_operation.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -20,9 +33,9 @@ # Receive CloudEvents try: - receive_result = client.receive_cloud_events( + receive_result = client.receive( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10, ) diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py index 3f6e87b8e050..7743fe3de606 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_reject_operation.py +DESCRIPTION: + These samples demonstrate rejecting CloudEvents. +USAGE: + python sample_reject_operation.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -19,11 +32,11 @@ # Release a LockToken try: - lock_tokens = RejectOptions(lock_tokens=["token"]) - reject_events = client.reject_cloud_events( + lock_tokens = ["token"] + reject_events = client.reject( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - reject_options=lock_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens, ) print(reject_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py index 8d7df562004a..cb0858e01666 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_release_operation.py +DESCRIPTION: + These samples demonstrate releasing CloudEvents. +USAGE: + python sample_release_operation.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -19,12 +32,12 @@ # Release a LockToken try: - lock_tokens = ReleaseOptions(lock_tokens=["token"]) - release_events = client.release_cloud_events( + lock_tokens = ["token"] + release_events = client.release( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, + subscription_name=EVENT_SUBSCRIPTION_NAME, release_delay_in_seconds=3600, - release_options=lock_tokens, + lock_tokens=lock_tokens, ) print(release_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py index 82a4fd9f5f47..52796dc9b1a2 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py @@ -3,6 +3,19 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +""" +FILE: sample_renew_locks_operation.py +DESCRIPTION: + These samples demonstrate renew locks CloudEvents. +USAGE: + python sample_renew_locks_operation.py + Set the environment variables with your own values before running the sample: + 1) EVENTGRID_KEY - The access key of your eventgrid account. + 2) EVENTGRID_ENDPOINT - The namespace endpoint. Typically it exists in the format + "https://..eventgrid.azure.net". + 3) EVENTGRID_TOPIC_NAME - The namespace topic name. + 4) EVENTGRID_EVENT_SUBSCRIPTION_NAME - The event subscription name. +""" import os from azure.core.credentials import AzureKeyCredential from azure.eventgrid import EventGridClient @@ -19,11 +32,11 @@ # Renew a lockToken try: - lock_tokens = RenewLockOptions(lock_tokens=["token"]) - release_events = client.renew_cloud_event_locks( + lock_tokens = ["token"] + release_events = client.renew_locks( topic_name=TOPIC_NAME, - event_subscription_name=EVENT_SUBSCRIPTION_NAME, - renew_lock_options=lock_tokens, + subscription_name=EVENT_SUBSCRIPTION_NAME, + lock_tokens=lock_tokens, ) print(release_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_authentication.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_authentication.py index eb54049d0925..a70aa2965b75 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_authentication.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_authentication.py @@ -6,7 +6,7 @@ """ FILE: sample_authentication.py DESCRIPTION: - These samples demonstrate authenticating an EventGridPublisherClient. + These samples demonstrate authenticating an EventGridClient. USAGE: python sample_authentication.py Set the environment variables with your own values before running the sample: @@ -17,33 +17,33 @@ """ # [START client_auth_with_key_cred] import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient from azure.core.credentials import AzureKeyCredential -topic_key = os.environ["EVENTGRID_TOPIC_KEY"] -endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] +key = os.environ["EVENTGRID_KEY"] +endpoint = os.environ["EVENTGRID_ENDPOINT"] -credential_key = AzureKeyCredential(topic_key) -client = EventGridPublisherClient(endpoint, credential_key) +credential_key = AzureKeyCredential(key) +client = EventGridClient(endpoint, credential_key) # [END client_auth_with_key_cred] # [START client_auth_with_sas_cred] import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient from azure.core.credentials import AzureSasCredential signature = os.environ["EVENTGRID_SAS"] endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] credential_sas = AzureSasCredential(signature) -client = EventGridPublisherClient(endpoint, credential_sas) +client = EventGridClient(endpoint, credential_sas, level="Basic") # [END client_auth_with_sas_cred] # [START client_auth_with_token_cred] from azure.identity import DefaultAzureCredential -from azure.eventgrid import EventGridPublisherClient, EventGridEvent +from azure.eventgrid import EventGridClient, EventGridEvent default_az_credential = DefaultAzureCredential() -endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] -client = EventGridPublisherClient(endpoint, default_az_credential) +endpoint = os.environ["EVENTGRID_ENDPOINT"] +client = EventGridClient(endpoint, default_az_credential) # [END client_auth_with_token_cred] diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cloud_event_using_dict.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cloud_event_using_dict.py index 0630d409ebd6..260bf1b16ff2 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cloud_event_using_dict.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cloud_event_using_dict.py @@ -16,14 +16,14 @@ "https://..eventgrid.azure.net/api/events". """ import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient 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) +client = EventGridClient(endpoint, credential, level="Basic") # [START publish_cloud_event_dict] client.send( diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cncf_cloud_events.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cncf_cloud_events.py index 83432366aa74..5fdecaf7ecf2 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cncf_cloud_events.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_cncf_cloud_events.py @@ -15,7 +15,7 @@ "https://..eventgrid.azure.net/api/events". """ import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient from azure.core.credentials import AzureKeyCredential from cloudevents.http import CloudEvent @@ -23,7 +23,7 @@ endpoint = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT"] credential = AzureKeyCredential(topic_key) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level="Basic") client.send( [ diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_custom_schema_to_a_topic.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_custom_schema_to_a_topic.py index 4650aae15d61..978a9002bc45 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_custom_schema_to_a_topic.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_custom_schema_to_a_topic.py @@ -22,7 +22,7 @@ import datetime as dt from azure.core.credentials import AzureKeyCredential -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient key = os.environ["EVENTGRID_CUSTOM_EVENT_TOPIC_KEY"] endpoint = os.environ["EVENTGRID_CUSTOM_EVENT_TOPIC_ENDPOINT"] @@ -31,7 +31,7 @@ def publish_event(): # authenticate client credential = AzureKeyCredential(key) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") # [START publish_custom_schema] custom_schema_event = { diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_event_using_dict.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_event_using_dict.py index b7154a0e07b8..4fc92b61b925 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_event_using_dict.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_event_using_dict.py @@ -19,7 +19,7 @@ import os from datetime import datetime from msrest.serialization import UTC -from azure.eventgrid import EventGridPublisherClient, EventGridEvent +from azure.eventgrid import EventGridClient, EventGridEvent from azure.core.credentials import AzureKeyCredential topic_key = os.environ["EVENTGRID_TOPIC_KEY"] @@ -29,7 +29,7 @@ def publish(): # [START publish_eg_event_dict] credential = AzureKeyCredential(topic_key) - client = EventGridPublisherClient(endpoint, credential) + client = EventGridClient(endpoint, credential, level="Basic") event0 = { "eventType": "Contoso.Items.ItemReceived", diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_domain.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_domain.py index 960f91aeae70..67c7bc725dbd 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_domain.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_domain.py @@ -15,14 +15,14 @@ "https://..eventgrid.azure.net/api/events". """ import os -from azure.eventgrid import EventGridPublisherClient, EventGridEvent +from azure.eventgrid import EventGridClient, EventGridEvent from azure.core.credentials import AzureKeyCredential domain_key = os.environ["EVENTGRID_DOMAIN_KEY"] domain_hostname = os.environ["EVENTGRID_DOMAIN_ENDPOINT"] credential = AzureKeyCredential(domain_key) -client = EventGridPublisherClient(domain_hostname, credential) +client = EventGridClient(domain_hostname, credential, level="Basic") client.send( [ diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_topic.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_topic.py index a0e3ab58b6dc..742a2080bb19 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_topic.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_eg_events_to_a_topic.py @@ -16,14 +16,14 @@ """ # [START publish_eg_event_to_topic] import os -from azure.eventgrid import EventGridPublisherClient, EventGridEvent +from azure.eventgrid import EventGridClient, 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 = EventGridClient(endpoint, credential, level="Basic") client.send( [ diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_to_a_topic_using_sas_credential.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_to_a_topic_using_sas_credential.py index 6051d883fbd4..48a66df61e8a 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_to_a_topic_using_sas_credential.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_to_a_topic_using_sas_credential.py @@ -16,14 +16,14 @@ "https://..eventgrid.azure.net/api/events". """ import os -from azure.eventgrid import EventGridPublisherClient, EventGridEvent, generate_sas +from azure.eventgrid import EventGridClient, EventGridEvent, generate_sas from azure.core.credentials import AzureKeyCredential, AzureSasCredential sas = os.environ["EVENTGRID_SAS"] endpoint = os.environ["EVENTGRID_TOPIC_ENDPOINT"] credential = AzureSasCredential(sas) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level="Basic") client.send( [ diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py index a0297f9950a3..abc4bec0cb3f 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_events_using_cloud_events_1.0_schema.py @@ -16,7 +16,7 @@ """ # [START publish_cloud_event_to_topic] import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent @@ -24,7 +24,7 @@ endpoint = os.environ["EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT"] credential = AzureKeyCredential(topic_key) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level="Basic") client.send( [ diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_to_channel.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_to_channel.py index 433ce0fefe72..1bed2ad38113 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_to_channel.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/sample_publish_to_channel.py @@ -17,7 +17,7 @@ """ # [START publish_cloud_event_to_topic] import os -from azure.eventgrid import EventGridPublisherClient +from azure.eventgrid import EventGridClient from azure.core.credentials import AzureKeyCredential from azure.core.messaging import CloudEvent @@ -27,7 +27,7 @@ channel_name = os.environ["EVENTGRID_PARTNER_CHANNEL_NAME"] credential = AzureKeyCredential(topic_key) -client = EventGridPublisherClient(endpoint, credential) +client = EventGridClient(endpoint, credential, level="Basic") client.send( [ diff --git a/sdk/eventgrid/azure-eventgrid/tests/conftest.py b/sdk/eventgrid/azure-eventgrid/tests/conftest.py index c69c75af758e..0676dd77c87d 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/conftest.py +++ b/sdk/eventgrid/azure-eventgrid/tests/conftest.py @@ -58,6 +58,22 @@ def add_sanitizers(test_proxy): eventgrid_client_secret = os.getenv("EVENTGRID_CLIENT_SECRET", "sanitized") tenant_id = os.getenv("AZURE_TENANT_ID", "sanitized") eventgrid_topic_endpoint = os.getenv("EVENTGRID_TOPIC_ENDPOINT", "sanitized") + + eventgrid_endpoint = os.getenv("EVENTGRID_ENDPOINT", "sanitized") + eventgrid_key = os.getenv("EVENTGRID_KEY", "sanitized") + eventgrid_topic_name = os.getenv("EVENTGRID_TOPIC_NAME", "sanitized") + eventgrid_event_subscription_name = os.getenv("EVENTGRID_EVENT_SUBSCRIPTION_NAME", "sanitized") + + eventgrid_cloud_event_topic_key = os.getenv("EVENTGRID_CLOUD_EVENT_TOPIC_KEY", "sanitized") + eventgrid_cloud_event_topic_endpoint = os.getenv("EVENTGRID_CLOUD_EVENT_TOPIC_ENDPOINT", "sanitized") + + eventgrid_topic_key = os.getenv("EVENTGRID_TOPIC_KEY", "sanitized") + eventgrid_topic_endpoint = os.getenv("EVENTGRID_TOPIC_ENDPOINT", "sanitized") + + eventgrid_partner_channel_name=os.getenv("EVENTGRID_PARTNER_CHANNEL_NAME", "sanitized") + eventgrid_partner_namespace_topic_endpoint=os.getenv("EVENTGRID_PARTNER_NAMESPACE_TOPIC_ENDPOINT", "sanitized") + eventgrid_partner_namespace_topic_key=os.getenv("EVENTGRID_PARTNER_NAMESPACE_TOPIC_KEY", "sanitized") + # Need to santize namespace for eventgrid_topic: try: eventgrid_hostname = urlparse(eventgrid_topic_endpoint).hostname diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py b/sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py new file mode 100644 index 000000000000..f3e28d500e09 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/tests/test_dual_client.py @@ -0,0 +1,287 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import pytest +from datetime import datetime +from devtools_testutils import AzureRecordedTestCase, recorded_by_proxy +from azure.eventgrid import EventGridClient, EventGridEvent, ClientLevel +from azure.eventgrid.models import * +from azure.core.messaging import CloudEvent +from azure.core.credentials import AzureKeyCredential +from azure.core.exceptions import HttpResponseError, ResourceNotFoundError +from cloudevents.http import CloudEvent as CNCFCloudEvent + +from eventgrid_preparer import EventGridPreparer + +class ArgPasser: + def __call__(self, fn): + def _preparer(test_class, level, **kwargs): + fn(test_class, level, **kwargs) + return _preparer + +class TestEGDualClient(AzureRecordedTestCase): + def create_eg_client(self, endpoint, key, level): + client = EventGridClient( + endpoint=endpoint, credential=AzureKeyCredential(key), level=level + ) + return client + + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_create_client_publish(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + from xml.etree import ElementTree as ET + xml_string = """test""" + tree = xml_string.encode('utf-8') + event = CloudEvent( + type="Contoso.Items.ItemReceived", + source="source", + subject="MySubject", + data=tree, + datacontenttype="text/xml", + extensions={"extension1": "value1", "extension2": "value2"} + ) + + if level=="Basic": + with pytest.raises(ValueError): + client.send( + topic_name=eventgrid_topic_name, events=event, binary_mode=True + ) + else: + client.send( + topic_name=eventgrid_topic_name, events=event, binary_mode=True + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_create_client_receive(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + from xml.etree import ElementTree as ET + xml_string = """test""" + tree = xml_string.encode('utf-8') + event = CloudEvent( + type="Contoso.Items.ItemReceived", + source="source", + subject="MySubject", + data=tree, + datacontenttype="text/xml", + extensions={"extension1": "value1", "extension2": "value2"} + ) + + if level=="Basic": + with pytest.raises(AttributeError): + client.receive( + topic_name=eventgrid_topic_name, subscription_name=eventgrid_event_subscription_name + ) + else: + client.receive( + topic_name=eventgrid_topic_name, subscription_name=eventgrid_event_subscription_name + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_create_client_publish_event(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, + eventgrid_topic_key, eventgrid_topic_endpoint): + if level=="Basic": + client = self.create_eg_client(eventgrid_topic_endpoint, eventgrid_topic_key, level=level) + else: + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + event = EventGridEvent( + id="7f7d", + subject="MySubject", + data={ + "test": "data" + }, + event_type="Contoso.Items.ItemReceived", + data_version="1.0" + ) + + if level=="Basic": + client.send( + events=event + ) + else: + with pytest.raises(TypeError): + client.send( + topic_name=eventgrid_topic_name, events=event + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_create_client_cloud_event(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, + eventgrid_cloud_event_topic_key, eventgrid_cloud_event_topic_endpoint): + if level=="Basic": + client = self.create_eg_client(eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level) + else: + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + event = CloudEvent( + type="Contoso.Items.ItemReceived", + source="source", + subject="MySubject", + data={"test": "data"}, + datacontenttype="application/json", + extensions={"extension1": "value1", "extension2": "value2"} + ) + + client.send( + topic_name=eventgrid_topic_name, events=event + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_create_client_channel_name(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, + eventgrid_partner_namespace_topic_key, eventgrid_partner_namespace_topic_endpoint, eventgrid_partner_channel_name): + + client = self.create_eg_client(eventgrid_partner_namespace_topic_endpoint, eventgrid_partner_namespace_topic_key, level=level) + + event = CloudEvent( + type="Contoso.Items.ItemReceived", + source="source", + subject="MySubject", + data={"test": "data"}, + datacontenttype="application/json", + extensions={"extension1": "value1", "extension2": "value2"} + ) + + if level=="Standard": + with pytest.raises(ValueError): + client.send( + topic_name=eventgrid_topic_name, events=event, channel_name=eventgrid_partner_channel_name + ) + else: + client.send( + topic_name=eventgrid_topic_name, events=event, channel_name=eventgrid_partner_channel_name + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_publish_endpoint(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): + + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + event = CloudEvent( + type="Contoso.Items.ItemReceived", + source="source", + subject="MySubject", + data={"test": "data"}, + datacontenttype="application/json", + extensions={"extension1": "value1", "extension2": "value2"} + ) + + if level=="Basic": + with pytest.raises(ResourceNotFoundError): + client.send( + topic_name=eventgrid_topic_name, events=event + ) + else: + client.send( + topic_name=eventgrid_topic_name, events=event + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_publish_cncf_events(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, + eventgrid_cloud_event_topic_key, eventgrid_cloud_event_topic_endpoint): + if level=="Basic": + client = self.create_eg_client(eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level) + else: + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + attributes = { + "type": "com.example.sampletype1", + "source": "https://example.com/event-producer", + } + data = {"message": "Hello World!"} + cloud_event = CNCFCloudEvent(attributes, data) + + if level==ClientLevel.STANDARD: + with pytest.raises(HttpResponseError): + client.send( + topic_name=eventgrid_topic_name, events=cloud_event + ) + else: + client.send( + topic_name=eventgrid_topic_name, events=cloud_event + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_create_client_cloud_event_dict(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, + eventgrid_cloud_event_topic_key, eventgrid_cloud_event_topic_endpoint): + if level=="Basic": + client = self.create_eg_client(eventgrid_cloud_event_topic_endpoint, eventgrid_cloud_event_topic_key, level=level) + else: + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + event = {"type": "Contoso.Items.ItemReceived", + "source": "source", + "subject": "MySubject", + "data": {"test": "data"}, + "datacontenttype": "application/json", + "extensions": {"extension1": "value1", "extension2": "value2"}} + + client.send( + topic_name=eventgrid_topic_name, events=event + ) + + @pytest.mark.live_test_only() + @pytest.mark.parametrize("level", ["Standard", "Basic"]) + @EventGridPreparer() + @ArgPasser() + @recorded_by_proxy + def test_create_client_publish_event_dict(self, level, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name, + eventgrid_topic_key, eventgrid_topic_endpoint): + if level=="Basic": + client = self.create_eg_client(eventgrid_topic_endpoint, eventgrid_topic_key, level=level) + else: + client = self.create_eg_client(eventgrid_endpoint, eventgrid_key, level=level) + + event = { + "eventType": "Contoso.Items.ItemReceived", + "data": {"itemSku": "Contoso Item SKU #1"}, + "subject": "Door1", + "dataVersion": "2.0", + "id": "randomuuid11", + "eventTime": datetime.now(), + } + + if level==ClientLevel.STANDARD: + with pytest.raises(TypeError): + client.send( + topic_name=eventgrid_topic_name, events=event + ) + else: + client.send( + topic_name=eventgrid_topic_name, events=event + ) \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py index d08679335a42..70a49863bb74 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py @@ -41,23 +41,19 @@ def test_publish_binary_mode_xml(self, eventgrid_endpoint, eventgrid_key, eventg extensions={"extension1": "value1", "extension2": "value2"} ) - client.publish_cloud_events( - eventgrid_topic_name, body=event, binary_mode=True + client.send( + topic_name=eventgrid_topic_name, events=event, binary_mode=True ) time.sleep(5) - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) - my_returned_event = events.value[0].event - assert my_returned_event.data == xml_string - assert my_returned_event.datacontenttype == 'text/xml' - assert my_returned_event.type == "Contoso.Items.ItemReceived" + events = client.receive(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) tokens = [] for detail in events.value: token = detail.broker_properties.lock_token tokens.append(token) - rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=RejectOptions(lock_tokens=tokens)) + rejected_result = client.reject(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens) @@ -75,23 +71,17 @@ def test_publish_binary_mode_cloud_event(self, eventgrid_endpoint, eventgrid_key datacontenttype='text/plain' ) - client.publish_cloud_events( - eventgrid_topic_name, body=event, binary_mode=True + client.send( + topic_name= eventgrid_topic_name, events=event, binary_mode=True ) - time.sleep(5) - - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) - my_returned_event = events.value[0].event - assert my_returned_event.data == 'this is binary data' - assert my_returned_event.datacontenttype == 'text/plain' - assert my_returned_event.type == "Contoso.Items.ItemReceived" + events = client.receive(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) tokens = [] for detail in events.value: token = detail.broker_properties.lock_token tokens.append(token) - rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=RejectOptions(lock_tokens=tokens)) + rejected_result = client.reject(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens) @EventGridPreparer() @@ -108,8 +98,8 @@ def test_publish_binary_mode_incorrect_cloud_event(self, eventgrid_endpoint, eve ) with pytest.raises(TypeError): - client.publish_cloud_events( - eventgrid_topic_name, body=event, binary_mode=True + client.send( + topic_name=eventgrid_topic_name, events=event, binary_mode=True ) @EventGridPreparer() @@ -126,8 +116,8 @@ def test_publish_binary_mode_list_cloud_event(self, eventgrid_endpoint, eventgri ) with pytest.raises(TypeError): - client.publish_cloud_events( - eventgrid_topic_name, body=[event], binary_mode=True + client.send( + topic_name=eventgrid_topic_name, events=[event], binary_mode=True ) @pytest.mark.live_test_only() @@ -147,23 +137,23 @@ def test_publish_binary_mode_combinations(self, eventgrid_endpoint, eventgrid_ke dict_event = {"type": "Contoso.Items.ItemReceived", "source": "source", "subject": "MySubject", "data": b"hello", "datacontenttype": "text/plain"} - client.publish_cloud_events( - eventgrid_topic_name, body=event, binary_mode=True + client.send( + topic_name=eventgrid_topic_name, events=event, binary_mode=True ) - client.publish_cloud_events( - eventgrid_topic_name, body=dict_event, binary_mode=True + client.send( + topic_name=eventgrid_topic_name, events=dict_event, binary_mode=True ) - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) + events = client.receive(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) tokens = [] for detail in events.value: token = detail.broker_properties.lock_token tokens.append(token) - rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=RejectOptions(lock_tokens=tokens)) + rejected_result = client.reject(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=tokens) - @pytest.mark.skip("need to update conftest") + @pytest.mark.live_test_only() @EventGridPreparer() @recorded_by_proxy def test_publish_receive_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): @@ -176,20 +166,20 @@ def test_publish_receive_cloud_event(self, eventgrid_endpoint, eventgrid_key, ev data=b'this is binary data', ) - client.publish_cloud_events( - eventgrid_topic_name, body=[event] + client.send( + topic_name=eventgrid_topic_name, events=[event] ) time.sleep(5) - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) + events = client.receive(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) lock_token = events.value[0].broker_properties.lock_token - ack = client.acknowledge_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=AcknowledgeOptions(lock_tokens=[lock_token])) + ack = client.acknowledge(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=[lock_token]) assert len(ack.succeeded_lock_tokens) == 1 assert len(ack.failed_lock_tokens) == 0 - @pytest.mark.skip("need to update conftest") + @pytest.mark.live_test_only() @EventGridPreparer() @recorded_by_proxy def test_publish_release_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): @@ -202,18 +192,18 @@ def test_publish_release_cloud_event(self, eventgrid_endpoint, eventgrid_key, ev data=b'this is binary data', ) - client.publish_cloud_events( - eventgrid_topic_name, body=[event] + client.send( + topic_name=eventgrid_topic_name, events=[event] ) time.sleep(5) - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) + events = client.receive(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) lock_token = events.value[0].broker_properties.lock_token - ack = client.release_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=ReleaseOptions(lock_tokens=[lock_token])) + ack = client.release(eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=[lock_token]) assert len(ack.succeeded_lock_tokens) == 1 assert len(ack.failed_lock_tokens) == 0 - events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) + events = client.receive(eventgrid_topic_name, eventgrid_event_subscription_name, max_events=1) assert events.value[0].broker_properties.delivery_count > 1 \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py index cfdec3f1c34d..b33ba86c2c3c 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py @@ -35,7 +35,7 @@ def test_publish_cloud_event_bad_request(self, eventgrid_endpoint, eventgrid_key ) with pytest.raises(HttpResponseError): - client.publish_cloud_events(eventgrid_topic_name, [event]) + client.send(topic_name=eventgrid_topic_name, events=[event]) @EventGridPreparer() @recorded_by_proxy @@ -49,7 +49,7 @@ def test_publish_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key): ) with pytest.raises(ResourceNotFoundError): - client.publish_cloud_events("faketopic", [event]) + client.send(topic_name="faketopic", events=[event]) @EventGridPreparer() @recorded_by_proxy @@ -57,7 +57,7 @@ def test_receive_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(ResourceNotFoundError): - client.receive_cloud_events("faketopic", eventgrid_event_subscription_name) + client.receive("faketopic", eventgrid_event_subscription_name) @EventGridPreparer() @recorded_by_proxy @@ -65,7 +65,7 @@ def test_receive_cloud_event_max_events_negative(self, eventgrid_endpoint, event client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( + client.receive( eventgrid_topic_name, eventgrid_event_subscription_name, max_events=-20 ) @@ -75,7 +75,7 @@ def test_receive_cloud_event_timeout_negative(self, eventgrid_endpoint, eventgri client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( + client.receive( eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=-20 ) @@ -85,7 +85,7 @@ def test_receive_cloud_event_timeout_max_value(self, eventgrid_endpoint, eventgr client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( + client.receive( eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=121 ) @@ -95,7 +95,7 @@ def test_receive_cloud_event_timeout_min_value(self, eventgrid_endpoint, eventgr client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(HttpResponseError): - client.receive_cloud_events( + client.receive( eventgrid_topic_name, eventgrid_event_subscription_name, max_wait_time=9 ) @@ -105,9 +105,9 @@ def test_acknowledge_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_k client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(ResourceNotFoundError): - lock_tokens = AcknowledgeOptions(lock_tokens=["faketoken"]) - client.acknowledge_cloud_events( - "faketopic", eventgrid_event_subscription_name, acknowledge_options=lock_tokens + lock_tokens = ["faketoken"] + client.acknowledge( + "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens ) @EventGridPreparer() @@ -116,20 +116,20 @@ def test_release_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) with pytest.raises(ResourceNotFoundError): - lock_tokens = ReleaseOptions(lock_tokens=["faketoken"]) - client.release_cloud_events( - "faketopic", eventgrid_event_subscription_name, release_options=lock_tokens + lock_tokens = ["faketoken"] + client.release( + "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens ) @EventGridPreparer() @recorded_by_proxy def test_reject_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) - lock_tokens = RejectOptions(lock_tokens=["faketoken"]) + lock_tokens = ["faketoken"] with pytest.raises(ResourceNotFoundError): - client.reject_cloud_events( - "faketopic", eventgrid_event_subscription_name, reject_options=lock_tokens + client.reject( + "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens ) @EventGridPreparer() @@ -137,9 +137,9 @@ def test_reject_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, e def test_acknowledge_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) - lock_tokens = AcknowledgeOptions(lock_tokens=["faketoken"]) - ack = client.acknowledge_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, acknowledge_options=lock_tokens + lock_tokens = ["faketoken"] + ack = client.acknowledge( + eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=lock_tokens ) assert type(ack) == AcknowledgeResult assert ack.succeeded_lock_tokens == [] @@ -151,9 +151,9 @@ def test_acknowledge_cloud_event_invalid_token(self, eventgrid_endpoint, eventgr def test_release_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) - lock_tokens = ReleaseOptions(lock_tokens=["faketoken"]) - release = client.release_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, release_options=lock_tokens + lock_tokens = ["faketoken"] + release = client.release( + eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=lock_tokens ) assert type(release) == ReleaseResult assert release.succeeded_lock_tokens == [] @@ -164,10 +164,10 @@ def test_release_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_k @recorded_by_proxy def test_reject_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) - lock_tokens = RejectOptions(lock_tokens=["faketoken"]) + lock_tokens = ["faketoken"] - reject = client.reject_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=lock_tokens + reject = client.reject( + eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=lock_tokens ) assert type(reject) == RejectResult assert reject.succeeded_lock_tokens == [] diff --git a/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py b/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py index 168feb277b4f..2824d8a2251b 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py +++ b/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py @@ -24,9 +24,10 @@ def test_binary_request_format(self): source="source", subject="MySubject", data=b'this is binary data', + datacontenttype="application/json" ) - request = _to_http_request("https://eg-topic.westus2-1.eventgrid.azure.net/api/events", event=event, binary_mode=True) + request = _to_http_request("https://MYTOPIC.westus2-1.eventgrid.azure.net/api/events", event=event) assert request.data == b"this is binary data" assert request.headers.get("ce-source") == "source" @@ -43,7 +44,7 @@ def test_binary_request_format_with_extensions_and_datacontenttype(self): extensions={"extension1": "value1", "extension2": "value2"} ) - request = _to_http_request("https://eg-topic.westus2-1.eventgrid.azure.net/api/events", event=event, binary_mode=True) + request = _to_http_request("https://MYTOPIC.westus2-1.eventgrid.azure.net/api/events", event=event) assert request.data == b"this is my data" assert request.headers.get("ce-source") == "source" @@ -63,5 +64,5 @@ def test_class_binary_request_format_error(self): ) with pytest.raises(TypeError): - _to_http_request("https://eg-topic.westus2-1.eventgrid.azure.net/api/events", event=event, binary_mode=True) + _to_http_request("https://MYTOPIC.westus2-1.eventgrid.azure.net/api/events", event=event)