Reputation: 2311
Below is the sample code copied from Microsoft's site. I did replace the Event Hubs <namespace>
, <eventhub>
, <AccessKeyName>
, and <primary key value>
with the required values.
import sys
import logging
import datetime
import time
import os
from azure.eventhub import EventHubClient, Sender, EventData
logger = logging.getLogger("azure")
# Address can be in either of these formats:
# "amqps://<URL-encoded-SAS-policy>:<URL-encoded-SAS-key>@<namespace>.servicebus.windows.net/eventhub"
# "amqps://<namespace>.servicebus.windows.net/<eventhub>"
# SAS policy and key are not required if they are encoded in the URL
ADDRESS = "amqps://<namespace>.servicebus.windows.net/<eventhub>"
USER = "<AccessKeyName>"
KEY = "<primary key value>"
try:
if not ADDRESS:
raise ValueError("No EventHubs URL supplied.")
# Create Event Hubs client
client = EventHubClient(ADDRESS, debug=False, username=USER, password=KEY)
sender = client.add_sender(partition="0")
client.run()
try:
start_time = time.time()
for i in range(100):
print("Sending message: {}".format(i))
message = "Message {}".format(i)
sender.send(EventData(message))
except:
raise
finally:
end_time = time.time()
client.stop()
run_time = end_time - start_time
logger.info("Runtime: {} seconds".format(run_time))
except KeyboardInterrupt:
pass
However, when I execute this code, I am getting below error.
Traceback (most recent call last):
File "newBlobStream.py", line 7, in <module>
from azure.eventhub import EventHubClient, Sender, EventData
ImportError: cannot import name 'EventHubClient' from 'azure.eventhub'
Upvotes: 2
Views: 6135
Reputation: 30025
The link you followed is a legacy one. As of now, the new version of azure-eventhub for python is v5 and is installed by default(when using pip install azure-eventhub
), please follow the code below to send events:
import asyncio
from azure.eventhub.aio import EventHubProducerClient
from azure.eventhub import EventData
async def run():
# create a producer client to send messages to the event hub
# specify connection string to your event hubs namespace and
# the event hub name
producer = EventHubProducerClient.from_connection_string(conn_str="EVENT HUBS NAMESPACE - CONNECTION STRING", eventhub_name="EVENT HUB NAME")
async with producer:
# create a batch
event_data_batch = await producer.create_batch()
# add events to the batch
event_data_batch.add(EventData('First event '))
event_data_batch.add(EventData('Second event'))
event_data_batch.add(EventData('Third event'))
# send the batch of events to the event hub
await producer.send_batch(event_data_batch)
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
And for more details about sending
/ receiving
events using the latest package, you can refer to this latest official doc.
Hope it helps.
Upvotes: 5
Reputation: 2042
pip install will pick new SDK which is 5.0 by default. The sample code won't runt with 5.0. Please install 1.3.1 of the Event Hubs SDK. It should work.
Upvotes: 1