繁体   English   中英

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

[英]Send events to Azure event hub using Python

下面是从微软网站复制的示例代码。 我确实用所需的值替换了事件中心<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-eventhub 新版本为 v5,默认安装(使用pip install azure-eventhub ),请按照以下代码发送事件:

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())

有关使用最新包sending / receiving事件的更多详细信息,您可以参考这个最新的官方文档

希望能帮助到你。

pip install 将选择默认为 5.0 的新 SDK。 示例代码不会与 5.0 一起运行。 请安装 1.3.1 的事件中心 SDK。 它应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM