Skip to content
This repository has been archived by the owner on Oct 12, 2023. It is now read-only.

Commit

Permalink
Merge pull request #24 from YijunXieMS/master
Browse files Browse the repository at this point in the history
Update sample to use latest version of Python Event Hubs package
  • Loading branch information
robinsh authored Jun 16, 2020
2 parents 4a7634e + a45f6ee commit 64467e9
Show file tree
Hide file tree
Showing 4 changed files with 184 additions and 1 deletion.
20 changes: 19 additions & 1 deletion iot-hub/Quickstarts/read-d2c-messages/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@ For an example that uses checkpointing, use the checkpoint store from

The above links have documentation on samples on how to use the checkpoint store.


## WebSocket and proxy

To use web socket, you need to specify param `transport_type` when creating the `EventHubConsumerClient`.
To use http proxy, you need to specify param `http_proxy` when creating the `EventHubConsumerClient`.
```python
from azure.eventhub import TrasnportType
from azure.eventhub.aio import EventHubConsumerClient # This is async API. For sync API, remove ".aio"
client = EventHubConsumerClient.from_connection_string(
conn_str=CONNECTION_STR,
consumer_group="$default",
transport_type=TransportType.AmqpOverWebsocket,
http_proxy={
'proxy_hostname': '<proxy host>',
'proxy_port': 3128,
'username': '<proxy user name>',
'password': '<proxy password>'
}
)
```


Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

"""
This sample demonstrates how to use the Microsoft Azure Event Hubs Client for Python async API to
read messages sent from a device. Please see the documentation for @azure/event-hubs package
for more details at https://pypi.org/project/azure-eventhub/
For an example that uses checkpointing, follow up this sample with the sample in the
azure-eventhub-checkpointstoreblob package on GitHub at the following link:
https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventhub/azure-eventhub-checkpointstoreblob-aio/samples/receive_events_using_checkpoint_store_async.py
"""


import asyncio
from azure.eventhub import TransportType
from azure.eventhub.aio import EventHubConsumerClient


# Event Hub-compatible endpoint
# az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {your IoT Hub name}
EVENTHUB_COMPATIBLE_ENDPOINT = "{your Event Hubs compatible endpoint}"

# Event Hub-compatible name
# az iot hub show --query properties.eventHubEndpoints.events.path --name {your IoT Hub name}
EVENTHUB_COMPATIBLE_PATH = "{your Event Hubs compatible name}"

# Primary key for the "service" policy to read messages
# az iot hub policy show --name service --query primaryKey --hub-name {your IoT Hub name}
IOTHUB_SAS_KEY = "{your service primary key}"

# If you have access to the Event Hub-compatible connection string from the Azure portal, then
# you can skip the Azure CLI commands above, and assign the connection string directly here.
CONNECTION_STR = f'Endpoint={EVENTHUB_COMPATIBLE_ENDPOINT}/;SharedAccessKeyName=service;SharedAccessKey={IOTHUB_SAS_KEY};EntityPath={EVENTHUB_COMPATIBLE_PATH}'

# Define callbacks to process events
async def on_event_batch(partition_context, events):
for event in events:
print("Received event from partition: {}.".format(partition_context.partition_id))
print("Telemetry received: ", event.body_as_str())
print("Properties (set by device): ", event.properties)
print("System properties (set by IoT Hub): ", event.system_properties)
print()
await partition_context.update_checkpoint()

async def on_error(partition_context, error):
# Put your code here. partition_context can be None in the on_error callback.
if partition_context:
print("An exception: {} occurred during receiving from Partition: {}.".format(
partition_context.partition_id,
error
))
else:
print("An exception: {} occurred during the load balance process.".format(error))


def main():
loop = asyncio.get_event_loop()
client = EventHubConsumerClient.from_connection_string(
conn_str=CONNECTION_STR,
consumer_group="$default",
# transport_type=TransportType.AmqpOverWebsocket, # uncomment it if you want to use web socket
# http_proxy={ # uncomment if you want to use proxy
# 'proxy_hostname': '127.0.0.1', # proxy hostname.
# 'proxy_port': 3128, # proxy port.
# 'username': '<proxy user name>',
# 'password': '<proxy password>'
# }
)
try:
loop.run_until_complete(client.receive_batch(on_event_batch=on_event_batch, on_error=on_error))
except KeyboardInterrupt:
print("Receiving has stopped.")
finally:
loop.run_until_complete(client.close())
loop.stop()


if __name__ == '__main__':
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

"""
This sample demonstrates how to use the Microsoft Azure Event Hubs Client for Python sync API to
read messages sent from a device. Please see the documentation for @azure/event-hubs package
for more details at https://pypi.org/project/azure-eventhub/
For an example that uses checkpointing, follow up this sample with the sample in the
azure-eventhub-checkpointstoreblob package on GitHub at the following link:
https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/eventhub/azure-eventhub-checkpointstoreblob/samples/receive_events_using_checkpoint_store.py
"""


from azure.eventhub import TransportType
from azure.eventhub import EventHubConsumerClient


# Event Hub-compatible endpoint
# az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {your IoT Hub name}
EVENTHUB_COMPATIBLE_ENDPOINT = "{your Event Hubs compatible endpoint}"

# Event Hub-compatible name
# az iot hub show --query properties.eventHubEndpoints.events.path --name {your IoT Hub name}
EVENTHUB_COMPATIBLE_PATH = "{your Event Hubs compatible name}"

# Primary key for the "service" policy to read messages
# az iot hub policy show --name service --query primaryKey --hub-name {your IoT Hub name}
IOTHUB_SAS_KEY = "{your service primary key}"

# If you have access to the Event Hub-compatible connection string from the Azure portal, then
# you can skip the Azure CLI commands above, and assign the connection string directly here.
CONNECTION_STR = f'Endpoint={EVENTHUB_COMPATIBLE_ENDPOINT}/;SharedAccessKeyName=service;SharedAccessKey={IOTHUB_SAS_KEY};EntityPath={EVENTHUB_COMPATIBLE_PATH}'

# Define callbacks to process events
def on_event_batch(partition_context, events):
for event in events:
print("Received event from partition: {}.".format(partition_context.partition_id))
print("Telemetry received: ", event.body_as_str())
print("Properties (set by device): ", event.properties)
print("System properties (set by IoT Hub): ", event.system_properties)
print()
partition_context.update_checkpoint()

def on_error(partition_context, error):
# Put your code here. partition_context can be None in the on_error callback.
if partition_context:
print("An exception: {} occurred during receiving from Partition: {}.".format(
partition_context.partition_id,
error
))
else:
print("An exception: {} occurred during the load balance process.".format(error))


def main():
client = EventHubConsumerClient.from_connection_string(
conn_str=CONNECTION_STR,
consumer_group="$default",
# transport_type=TransportType.AmqpOverWebsocket, # uncomment it if you want to use web socket
# http_proxy={ # uncomment if you want to use proxy
# 'proxy_hostname': '127.0.0.1', # proxy hostname.
# 'proxy_port': 3128, # proxy port.
# 'username': '<proxy user name>',
# 'password': '<proxy password>'
# }
)
try:
with client:
client.receive_batch(
on_event_batch=on_event_batch,
on_error=on_error
)
except KeyboardInterrupt:
print("Receiving has stopped.")

if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions iot-hub/Quickstarts/read-d2c-messages/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
azure-eventhub

0 comments on commit 64467e9

Please sign in to comment.