Azure Event Hubs Client Library

5.15.1 · active · verified Thu Apr 09

The Microsoft Azure Event Hubs Client Library for Python facilitates sending and receiving events to and from Azure Event Hubs. It follows the Azure SDK 'Track 2' design principles, offering an async-first API for high-throughput data streaming scenarios. The current version is 5.15.1, and it receives regular updates, typically monthly or bi-monthly, in alignment with other Azure SDKs.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to send a batch of events to an Azure Event Hub using the `EventHubProducerClient`. It uses environment variables for secure credential management and showcases the async API pattern, which is standard for the Track 2 Azure SDKs.

import os
import asyncio
from azure.eventhub import EventHubProducerClient, EventData

# Retrieve connection string and Event Hub name from environment variables.
# For local development, replace 'os.environ.get(...)' with your actual values.
# Connection string for Event Hubs Namespace, NOT a specific Event Hub.
CONNECTION_STR = os.environ.get("EVENT_HUB_CONNECTION_STR", "Endpoint=sb://<NAMESPACE>.servicebus.windows.net/;SharedAccessKeyName=<KEY_NAME>;SharedAccessKey=<KEY>")
# The specific Event Hub name within the namespace
EVENTHUB_NAME = os.environ.get("EVENT_HUB_NAME", "<YOUR_EVENT_HUB_NAME>")

async def send_events():
    producer = EventHubProducerClient.from_connection_string(
        conn_str=CONNECTION_STR,
        eventhub_name=EVENTHUB_NAME
    )
    async with producer:
        event_data_batch = await producer.create_batch()
        event_data_batch.add(EventData("Hello Azure Event Hubs!"))
        event_data_batch.add(EventData("This is my second event."))
        await producer.send_batch(event_data_batch)
    print("Sent a batch of two events successfully.")

if __name__ == "__main__":
    # Ensure you have set the EVENT_HUB_CONNECTION_STR and EVENT_HUB_NAME
    # environment variables or replaced the placeholders.
    if not CONNECTION_STR or '<NAMESPACE>' in CONNECTION_STR:
        print("Please set the EVENT_HUB_CONNECTION_STR and EVENT_HUB_NAME environment variables.")
        print("Example: export EVENT_HUB_CONNECTION_STR='Endpoint=sb://...;SharedAccessKeyName=...;SharedAccessKey=...'")
        print("Example: export EVENT_HUB_NAME='myhub'")
    else:
        asyncio.run(send_events())

view raw JSON →