快速入门:使用 Python(azure-eventhub 版本 1)向/从事件中心发送/接收事件Quickstart: Send and receive events with Event Hubs using Python (azure-eventhub version 1)

本快速入门介绍如何使用 azure-eventhub 版本 1 Python 包向事件中心发送事件以及从事件中心接收事件。This quickstart shows how to send events to and receive events from an event hub using the azure-eventhub version 1 Python package.

Warning

本快速入门使用旧的 azure-eventhub 版本 1 包。This quickstart uses the old azure-eventhub version 1 package. 有关使用该包的最新版本 5 的快速入门,请参阅使用 azure-eventhub 版本 5 发送和接收事件For a quickstart that uses the latest version 5 of the package, see Send and receive events using azure-eventhub version 5. 若要将应用程序从使用旧包迁移到使用新包,请参阅从 azure-eventhub 版本 1 迁移到版本 5 的指南To move your application from using the old package to new one, see the Guide to migrate from azure-eventhub version 1 to version 5.

先决条件Prerequisites

如果不熟悉 Azure 事件中心,请在阅读本快速入门之前参阅事件中心概述If you are new to Azure Event Hubs, see Event Hubs overview before you do this quickstart.

若要完成本快速入门,需要具备以下先决条件:To complete this quickstart, you need the following prerequisites:

  • Azure 订阅Azure subscription. 若要使用 Azure 服务(包括 Azure 事件中心),需要一个订阅。To use Azure services, including Azure Event Hubs, you need a subscription. 如果没有现有 Azure 帐户,可以注册 1 元试用版创建帐户If you don't have an existing Azure account, you can sign up for a 1mb trial or create an account.

  • Python 3.4 或更高版本,其中已安装并更新 pipPython 3.4 or later, with pip installed and updated.

  • 事件中心的 Python 包。The Python package for Event Hubs. 若要安装此包,请在路径中包含 Python 的命令提示符中运行以下命令:To install the package, run this command in a command prompt that has Python in its path:

    pip install azure-eventhub==1.3.*
    
  • 创建事件中心命名空间和事件中心Create an Event Hubs namespace and an event hub. 第一步是使用 Azure 门户创建事件中心类型的命名空间,并获取应用程序与事件中心进行通信所需的管理凭据。The first step is to use the Azure portal to create a namespace of type Event Hubs, and obtain the management credentials your application needs to communicate with the event hub. 要创建命名空间和事件中心,请按照此文中的步骤操作。To create a namespace and an event hub, follow the procedure in this article. 然后,按照文章中的以下说明获取事件中心访问密钥的值:获取连接字符串Then, get the value of access key for the event hub by following instructions from the article: Get connection string. 你将在本快速入门中稍后编写的代码中使用访问密钥。You use the access key in the code you write later in this quickstart. 默认密钥名称为:RootManageSharedAccessKey。The default key name is: RootManageSharedAccessKey.

发送事件Send events

若要创建将事件发送到事件中心的 Python 应用程序,请执行以下操作:To create a Python application that sends events to an event hub:

Note

可以从 GitHub 下载并运行示例应用,不需通过本快速入门来进行。Instead of working through the quickstart, you can download and run the sample apps from GitHub. EventHubConnectionStringEventHubName 字符串替换为事件中心的值。Replace the EventHubConnectionString and EventHubName strings with your event hub values.

  1. 打开你常用的 Python 编辑器,例如 Visual Studio CodeOpen your favorite Python editor, such as Visual Studio Code

  2. 创建名为 send.py 的新文件。Create a new file called send.py. 此脚本将向事件中心发送 100 个事件。This script sends 100 events to your event hub.

  3. 将下列代码粘贴到“send.py”,将事件中心 <namespace>、<eventhub>、<AccessKeyName> 和 <primary key value> 替换为你的值:Paste the following code into send.py, replacing the Event Hubs <namespace>, <eventhub>, <AccessKeyName>, and <primary key value> with your 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.chinacloudapi.cn/eventhub"
    # "amqps://<namespace>.servicebus.chinacloudapi.cn/<eventhub>"
    # SAS policy and key are not required if they are encoded in the URL
    
    ADDRESS = "amqps://<namespace>.servicebus.chinacloudapi.cn/<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
    
  4. 保存文件。Save the file.

若要运行脚本,请从保存 send.py 的目录运行以下命令:To run the script, from the directory where you saved send.py, run this command:

start python send.py

祝贺!Congratulations! 现在已向事件中心发送消息。You have now sent messages to an event hub.

接收事件Receive events

若要创建从事件中心接收事件的 Python 应用程序,请执行以下操作:To create a Python application that receives events from an event hub:

  1. 在 Python 编辑器中,创建名为 recv.py 的文件。In your Python editor, create a file called recv.py.

  2. 将下列代码粘贴到“recv.py”,将事件中心 <namespace>、<eventhub>、<AccessKeyName> 和 <primary key value> 替换为你的值:Paste the following code into recv.py, replacing the Event Hubs <namespace>, <eventhub>, <AccessKeyName>, and <primary key value> with your values:

    import os
    import sys
    import logging
    import time
    from azure.eventhub import EventHubClient, Receiver, Offset
    
    logger = logging.getLogger("azure")
    
    # Address can be in either of these formats:
    # "amqps://<URL-encoded-SAS-policy>:<URL-encoded-SAS-key>@<mynamespace>.servicebus.chinacloudapi.cn/myeventhub"
    # "amqps://<namespace>.servicebus.chinacloudapi.cn/<eventhub>"
    # SAS policy and key are not required if they are encoded in the URL
    
    ADDRESS = "amqps://<namespace>.servicebus.chinacloudapi.cn/<eventhub>"
    USER = "<AccessKeyName>"
    KEY = "<primary key value>"
    
    
    CONSUMER_GROUP = "$default"
    OFFSET = Offset("-1")
    PARTITION = "0"
    
    total = 0
    last_sn = -1
    last_offset = "-1"
    client = EventHubClient(ADDRESS, debug=False, username=USER, password=KEY)
    try:
        receiver = client.add_receiver(
            CONSUMER_GROUP, PARTITION, prefetch=5000, offset=OFFSET)
        client.run()
        start_time = time.time()
        for event_data in receiver.receive(timeout=100):
            print("Received: {}".format(event_data.body_as_str(encoding='UTF-8')))
            total += 1
    
        end_time = time.time()
        client.stop()
        run_time = end_time - start_time
        print("Received {} messages in {} seconds".format(total, run_time))
    
    except KeyboardInterrupt:
        pass
    finally:
        client.stop()
    
  3. 保存文件。Save the file.

若要运行脚本,请从保存 recv.py 的目录运行以下命令:To run the script, from the directory where you saved recv.py, run this command:

start python recv.py

后续步骤Next steps

有关事件中心的详细信息,请参阅以下文章:For more information about Event Hubs, see the following articles: