使用Python将事件发送到Azure事件中心

问题描述 投票:0回答:2

下面是从Microsoft的site复制的示例代码。我确实用所需的值替换了事件中心<namespace><eventhub><AccessKeyName><primary key value>

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

但是,当我执行此代码时,出现错误提示。

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'
python azure azure-eventhub azure-eventhub-capture
2个回答
0
投票

pip install将选择默认为5.0的新SDK。该示例代码不会在5.0中破烂。请安装1.3.1的事件中心SDK。应该可以。


0
投票

您关注的link是旧版。截至目前,适用于python的azure-eventhub的新版本为v5,并且默认情况下已安装(使用pip install azure-eventhub时),请按照以下代码发送事件:

© www.soinside.com 2019 - 2024. All rights reserved.